add record to a file in java - javascript

guys i am using jqgrid .. here is my file
{
"rows":[
{"OrderID":"10248","FromDate":"1996-07-04","CustomerID":"WILMK","ShipName":"Vins et alcools Chevalier","ToDate":"1996-07-05"},
{"OrderID":"10249","FromDate":"1996-07-05","CustomerID":"TRADH","ShipName":"Toms Spezialit\u00e4ten","ToDate":"1996-07-17"},
{"OrderID":"10250","FromDate":"1996-07-08","CustomerID":"HANAR","ShipName":"Hanari Carnes","ToDate":"1996-07-26"},
{"OrderID":"10251","FromDate":"1996-07-08","CustomerID":"VICTE","ShipName":"Victuailles en stock","ToDate":"1996-08-01"},
{"OrderID":"10277","FromDate":"1996-08-09","CustomerID":"MORGK","ShipName":"Morgenstern Gesundkost","ToDate":"1996-08-12"}
]
}
but i want it to be like
{
"rows":[
{"OrderID":"10248","FromDate":"1996-07-04","CustomerID":"WILMK","ShipName":"Vins et alcools Chevalier","ToDate":"1996-07-05"},
{"OrderID":"10249","FromDate":"1996-07-05","CustomerID":"TRADH","ShipName":"Toms Spezialit\u00e4ten","ToDate":"1996-07-17"},
{"OrderID":"10250","FromDate":"1996-07-08","CustomerID":"HANAR","ShipName":"Hanari Carnes","ToDate":"1996-07-26"},
{"OrderID":"10251","FromDate":"1996-07-08","CustomerID":"VICTE","ShipName":"Victuailles en stock","ToDate":"1996-08-01"},
{"OrderID":"10277","FromDate":"1996-08-09","CustomerID":"MORGK","ShipName":"Morgenstern Gesundkost","ToDate":"1996-08-12"},
{"OrderID":"10261","FromDate":"1996-07-19","CustomerID":"QUEDE","ShipName":"Que Del\u00edcia","ToDate":"1996-08-09"} // added row
]
}

From your question it seems like, you want to add another object in json file within an array. So, here is a solution.
Read your json file with whatever library you are using to read/write json from files.
Add the new object in the specific list.
Write that to file with over write mode.

First parse your JSON content:
String input = "{\"rows\":[{\"OrderID\":\"10248\"}]}";
JSONObject json = new JSONObject(input);
Then get the array from the parsed content:
JSONArray arr = json.getJSONArray("rows");
Convert the object to add to JSON:
JSONObject newRow = new JSONObject();
newRow.accumulate("OrderID", 10000);
// Do the same for all your attributes
And finally add the new row to the array to get your updated JSON:
arr.put(newRow);
String updatedJSON = json.toString();

you want to add another object in json file within an array. So, here is a solution.
Read your json file.
Put your key row as a JSONArray and Store it into a String.
Construct a Class Order.
Class Order
{
String OrderID ;
String FromDate ;
String CustomerID
String ShipName;
String ToDate;
}
Add the new object in the specific list.
//import Class (add a jar com.fasterxml.jackson to your project)
import com.fasterxml.jackson.databind.ObjectMapper;
// Here I assume that "applicationArray" contains the Array .
String applicationArray = "[
{"OrderID":"10248","FromDate":"1996-07-04","CustomerID":"WILMK","ShipName":"Vins et alcools Chevalier","ToDate":"1996-07-05"},
{"OrderID":"10249","FromDate":"1996-07-05","CustomerID":"TRADH","ShipName":"Toms Spezialit\u00e4ten","ToDate":"1996-07-17"},
{"OrderID":"10250","FromDate":"1996-07-08","CustomerID":"HANAR","ShipName":"Hanari Carnes","ToDate":"1996-07-26"},
{"OrderID":"10251","FromDate":"1996-07-08","CustomerID":"VICTE","ShipName":"Victuailles en stock","ToDate":"1996-08-01"},
{"OrderID":"10277","FromDate":"1996-08-09","CustomerID":"MORGK","ShipName":"Morgenstern Gesundkost","ToDate":"1996-08-12"},
{"OrderID":"10261","FromDate":"1996-07-19","CustomerID":"QUEDE","ShipName":"Que Del\u00edcia","ToDate":"1996-08-09"} // added row
]"
ObjectMapper mapper = new ObjectMapper();
List<Order> obj_listOrder = mapper.readValue(applicationArray, mapper.getTypeFactory().constructCollectionType(List.class, DeviceApplication.class));
Now add one more element to the list .
Add One More element to the List.
Replace the content of Your file.

Related

add a property to a Json array with Gson

I am serializing a list of objects with Gson like this:
String responseMessage = new Gson().toJson(pages.get(pagenumber));
I want to add another property to be read in javascript but that is unrelated to the list:
{"numberofpages":x}
I tried this:
JsonElement responsemessage = new Gson().toJsonTree(pages.get(pagenumber));
JsonObject message = (JsonObject) responsemessage;
message.addProperty("numberofpages",numberofpages);
... but I couldn't because responsemessage was a JSONArray. How can I encode more information in this String version of responseMessage to be read in javascript:
$.get("/lod1/Data",{pagenumber: page},function(list){
console.log(list);
//???
//if(list.numberofpages == 5){
// }
$.each(list,function(index,card){
$("#questionsforsets").append('<tr><td class="questioncell"><div class="longtexttd">'+card.card+'</div></td><td>'+card.category+'</td><td>'+card.made+'</td><td>'+card.missed+'</td></tr>');
});
},"json");
Well, as you found out, you cant add a property to a JSON Array.
If your responsemessage is an array, and you need to pass another value along with it, you should put this array and that value into a new object. Something like this should work:
JsonObject responseObject = new JsonObject();
responseObject.addProperty("pages", responsemessage);
responseObject.addProperty("numOfPages", numberOfPages);
(of course your JS code handling this response will need to be adjusted accordingly)

How to get int array with javascript in play framework template?

When I tried to pass a list to the template I got an error.
The list is defined like:
myList: List<Map<String,int[]>>
Now the data of myList is :
[{First Try=[1,0,0,1], Second Try=[1,1,2,2]}, {}]
I use chart.js to show a chart and so I need a int[] as data list.
my view:
#(myList: List[Map[String,Array[Int]]])
var list = #myList;
for(var i=0;i<list.length;i++){
var map = list[i];
for(var key in map){
myFunction(key,map[key]);
}
}
myFunction(string,array){
//I want directly use the array to the chart’s datasets
//others
var myChart = new Chart(chartid, {
type: 'bar',
data: {
labels: [“a”, “b", “c”, ”s”],
datasets: [{
data: array
}]
}
}
But I got error when I try to traversal the List (The error line shown with Chrome debug)
var out = [{First Try=[I#6e37161d, Second Try=[I#5788d8a9}, {}];
// “Uncaught SyntaxError: Invalid or unexpected token”.
I know when directly output array with
System.out.println(array);
in java it will happen with the string like [I#6e37161d, but I don’t know how to deal with it in javascript.How can I use this array?I will be grateful if anyone can help .
Thank you very much.
You can't convert the Java object directly to a Javascript variable like you're attempting to do.
var list = #myList;
That just takes myList.toString() and attempts to set that as a literal Javascript variable. You need to serialize your Java object to JSON first, then you can parse the JSON in Javascript. Like so:
// Java controller code
String myListJson = Json.stringify(Json.toJson(myList));
// Template
#(myListJson: String)
var list = JSON.parse("#myListJson");

Array is not serialized and resulting a string

A list that contains a set of arrays is being serialized into jquery. However when check in client side, it is receiving only a string instead of the array object.
c#:
public string jsscript(){
// datatable processing
var arrList = new List<object>();
foreach (DataRow row in table.Rows)
{
string name = row[0].ToString();
string quantity = row[1].ToString();
string balance = row[2].ToString();
string remove = "X";
arrList.Add( new[] { name, quantity, balance, remove });
}
return (new JavaScriptSerializer()).Serialize(arrList);
}
js:
<script>
//dom...
function theDomHasLoaded(e) {
dbdata = <%=jsscripts()%>;
</script>
see JSON string to JS object
you need to use JSON.parse(..) on the serialised string
that is of course presuming that that is the problem... It's not entirely clear what your problem is.

injecting strings in json objects

In java script I create a json var
var Token = { "TagItem": { "TagList": [tags] } };
where tags is
"AA","BB","CCC","DDDD"
I call an asp mvc controller using ajax and I send the json to a method.
the desirialized json object is
public class TagItem
{
public List<string> TagList { get; set; }
}
and it is deserialized in ajax call to list with a single value of ["AA","BB","CCC","DDDD"].
instead of many values as if I would have writted
var data = { "tagItem": { "TagList": ["AA", "BB", "CCC", "DDDD"]} };
Which works great.
Idea on how to write it in js?
[tags] will create an array with only one element, tags.
If tags is a comma separated string like "AA,BB,CCC,DDDD", then you can use .split to transform it into an array.
var Token = { "TagItem": { "TagList": tags.split(',') } };
UPDATE: After seeing the screenshot you posted (http://i.imgur.com/IzSGS8L.png), I see what the real error here is. It's how you are creating tags.
You don't need to add ", or ,. You are just building an array/an object, you are not building a string. .map returns you an array, no need to convert it a string using .join, just use it as an array.
var tags = $('#myTags input[name="tags"]').map(function(){
return $(this).val();
}).get();
var Token = { "TagItem": { "TagList": tags } };
Note: There are no [] around tags. That's because it's already an array, no need to add it to another array.

How to append database values to JSON data

I have a JSON which lists the values from database. Below is the JSON data of 2 rows from the database.
[{"Name":"P1","Description":"pd1","Value":"v1","Attribute":"a1"},{"Name":"P1","Description":"pd1","Value":"v2","Attribute":"a2"}]
database values are the result of a left join query. Only 'Value' and 'Attribute' fields are different. Can I append that fields to JSON instead of multiple sets of record? I know there is 'push' to do this, but I am unaware where and how to use this in my code. below is the code for fetching values from db and serializing the values.
GetProfileDataService GetProfileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
IEnumerable<ProfileData> ProfileDetails = GetProfileDataService.GetList(new ProfileSearchCriteria { Name = strProfileName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string strSerProfileDetails = javaScriptSerializer.Serialize(ProfileDetails);
context.Response.ContentType = "text/json";
context.Response.Write(strSerProfileDetails);
Below is my getJSON
$(document).ready(function () {
$.getJSON('ProfileHandler.ashx', { 'ProfileName': 'Profile 1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute+' : '+v.Value);
});
});
});
Please help me here.
There are several things you can do.
Store value and attribute as arrays:
[{"Name":"P1","Description":"pd1","Value":["v1", "v2"],"Attribute":["a1", "a2"]}]
Or store them as a 'symbol'-separated string:
[{"Name":"P1","Description":"pd1","Value":"v1;v2"],"Attribute":"a1;a2"]}]
In order to use the first case, you'll have to try and figure out how to format the ProfileDetails in order to have javaScriptSerializer.Serialize parse it correctly. You will likely have to convert your data first in order for this to work (i.e. convert value and attribute to arrays).
For the second case to work you could modify your GetProfileDataService.GetList method so that values and attributes are merged to symbol-separated strings (something like this: GROUP BY to combine/concat a column)

Categories