Hi i have a problem regarding the merge of JSONArray inside JSONObject. Below is what my JSONObject looks like:
{
"name":"sample.bin.png",
"coords":{
"1":{"x":[ 974, 975],"y":[154, 155},
"3":{"x":[124, 125],"y":[529]},
"8":{"x":[2048, 2049],"y":[548, 560, 561, 562, 563, 564 ]}
}
}
Now i have keys of those JSONObjects which i want to merge (inside coords).I wanted to merge x and y respectively into one JSONObject here is my code:
String[] tokens = request().body().asFormUrlEncoded().get("coords")[0].split(","); //here i recieve the String Array Keys of the coords i want to merge
if (!image.equals("")) {
JSONObject outputJSON = getImageJSON(image); //here comes the JSON which i posted above
JSONObject coordsPack = (JSONObject) outputJSON.get("coords");
JSONObject merged = new JSONObject();
merged.put("x", new JSONArray());
merged.put("y", new JSONArray());
for (String index : tokens) {
JSONObject coordXY = (JSONObject) coordsPack.get(index);
JSONArray xList = (JSONArray) coordXY.get("x");
JSONArray yList = (JSONArray) coordXY.get("y");
merged.get("x").addAll(xList);
merged.get("y").addAll(yList);
}
System.out.println(merged);
}
but problem is that i am having error at merged.get("x").addAll(xList); and merged.get("y").addAll(yList); i am unable to access the methods.
You must fill the lists first, and you should take out these following lines out of for loop.
merged.get("x").addAll(xList);
merged.get("y").addAll(yList);
BTW, it's apoor design to achieve your goal.
Don't you need to cast it into JSONArray class first, like you did for the 2 lines above?
As per suggestion of #cihan seven i am able to get the answer of my problem here is my solution:
JSONObject coordsPack = (JSONObject) outputJSON.get("coords");
JSONObject merged = new JSONObject();
JSONArray xList = new JSONArray();
JSONArray yList = new JSONArray();
for (String index : tokens) {
JSONObject coordXY = (JSONObject) coordsPack.get(index);
xList.addAll((JSONArray) coordXY.get("x"));
yList.addAll((JSONArray) coordXY.get("y"));
}
merged.put("x", xList);
merged.put("y", yList);
System.out.println(merged);
Related
I have list of items adding in to JsonArray and convert this JsonArray to string and adding this string JsonObject as a property. But While I am getting response is with back slashs.
jsonObject.addProperty("name",rsmd.getColumnLabel(1));
JsonArray itemJsonArray = new JsonArray();
JsonArray jsonArray = new JsonArray();
while (resultSet.next()) {
itemJsonArray.add(resultSet.getString(1));
}
jsonObject.addProperty("items",itemJsonArray.toString());
jsonArray.add(jsonObject);
Output:
{
"name": "username",
"items": [\"Mohan\",\"Mohan\",\"Mohan\"]
}
Basically your problem is you are doing itemJsonArray.toString() and also you need to use add() instead of addProperty(), so:
Instead of
jsonObject.addProperty("items",itemJsonArray.toString());
Do this:
jsonObject.add("items",itemJsonArray);
im been working apps with booking system, and i have problem with generate json and send it to server. the server catch this json
"buy":{
"583":[
{
"title":"Mr",
"nama_depan":"Mulia Rifai Aroyan",
"nama_belakang":"",
"tanggal_lahir":"0000-0-0",
"nationality":"Indonesia",
"identitas":"identitas",
"kelas_id":"254",
"kelas":"B",
"harga":"60000",
"seat":""
}
],
"584":[
{
"title":"Mr",
"nama_depan":"Mulia Rifai Aroyan",
"nama_belakang":"",
"tanggal_lahir":"0000-0-0",
"nationality":"Indonesia",
"identitas":"identitas",
"kelas_id":"254",
"kelas":"B",
"harga":"60000",
"seat":""
}
]
}
and i create generated json like this :
final JSONObject buy_child = new JSONObject();
final JSONArray buy = new JSONArray();
final JSONObject detail = new JSONObject();
for (int i=0;i<list_id_content.size();i++)
{
detail.put("title",gelar);
detail.put("nama_depan",nama_depan);
detail.put("nama_belakang",nama_belakang);
detail.put("tanggal_lahir",tanggal_lahir);
detail.put("nationality",nationality);
detail.put("identitas",identitas);
detail.put("kelas_id",id_event);
detail.put("kelas",kelas);
detail.put("harga",total_harga_pertiket);
detail.put("seat","");
buy.put(detail);
buy_child.put(id_event_content2,buy);
}
but its seems only generate json with same value (the last value)
how can i generate json like that and get all the value inside the loop?
thanks
edited : if i put JSONObject detail = new JSONObject(); inside the loop, it will give me this
Put the JSONObject detail = new JSONObject(); inside the for loop at the beginning.
Then put buy.put(detail); at the end of the loop (but inside).
You're only getting the last one right now because the buy.put is outside the for loop.
try with this
final JSONObject buy_child = new JSONObject();
final JSONArray buy;
for (int i=0;i<list_id_content.size();i++)
{
buy= new JSONArray();
final JSONObject detail = new JSONObject();
detail.put("title",gelar);
detail.put("nama_depan",nama_depan);
detail.put("nama_belakang",nama_belakang);
detail.put("tanggal_lahir",tanggal_lahir);
detail.put("nationality",nationality);
detail.put("identitas",identitas);
detail.put("kelas_id",id_event);
detail.put("kelas",kelas);
detail.put("harga",total_harga_pertiket);
detail.put("seat","");
buy.put(detail);
}
buy_child.put(id_event_content2,buy);
I am trying to greate JSON with the JSON library. At the momant I am creating JSONArray to add to add all the value in my List to it but I am facing this Problem
he method put(int, boolean) in the type JSONArray is not applicable for the arguments (String, List)
at this line arrivalMoFr.put("mon-fri", timeEntries); How can I add List to the JSONArray?
I appreciate any help.
Code:
List<String> timeEntries = entry.getValue();
try {
JSONObject timeTable = new JSONObject();
timeTable.put("route", route);
JSONObject info = new JSONObject();
info.put("direction", direction);
JSONObject stops = new JSONObject();
stops.put("stops_name", key);
JSONObject arrivals = new JSONObject();
JSONArray arrivalMoFr = new JSONArray();
//The error is here.
arrivalMoFr.put("mon-fri", timeEntries);
arrivals.put("mon-fri", arrivalMoFr);
stops.put("arrival_time", arrivals);
info.put("stops", stops);
timeTable.put("info", info);
System.out.println(timeTable.toString(3));
}
Edit:
I added it like this but I am getting now this result:
JSONObject arrivals = new JSONObject();
JSONArray arrivalMoFr = new JSONArray();
arrivalMoFr.put( timeEntries);
arrivals.put("mon-fri", arrivalMoFr);
Result:
{
"route": "4",
"info": {
"stops": {
"arrival_time": {"mon-fri": [[
"05:04",
"18:41",
"19:11",
"19:41",
"20:11"
]]},
"stops_name": "Heiweg "
},
"direction": "Groß Grönau"
}
}
JSONArray att = new JSONArray(YourList);
You can use Gson to convert List<String> to JSON
List<String> listStrings = new ArrayList<String>();
listStrings.add("a");
listStrings.add("b");
Gson objGson = new Gson();
System.out.println(objGson.toJson(listStrings));
Output
["a","b"]
a json array is as given below
var data = [
{label:'gggg',data: [[(new Date('2011/12/01')).getTime(),53914],[(new Date('2012/1/02')).getTime(),32172],[(new Date('2012/2/03')).getTime(),824],[(new Date('2012/4/04')).getTime(),838],[(new Date('2012/6/05')).getTime(),755],[(new Date('2012/7/06')).getTime(),0],[(new Date('2012/8/07')).getTime(),0],[(new Date('2012/9/08')).getTime(),0],[(new Date('2012/10/09')).getTime(),0],[(new Date('2012/11/10')).getTime(),0],[(new Date('2012/12/11')).getTime(),0],[(new Date('2012/12/11')).getTime(),0]]}
];
in java class for creating the above similar json, i'm using the following code given below.
but the problem is there is a double quotes in each "(new Date(2012/12/01)).getTime()"
can anyone please tell me how to remove those double quotes
Query q1=session.createQuery("FROM VendorMonth");
List li1=q1.list();
String supname="",tempsupname;
JSONObject obj = new JSONObject();
JSONArray jsonarrmast = new JSONArray();
List s=new ArrayList();
JSONArray finals=new JSONArray();
JSONArray finalarray = new JSONArray();
for(int i=0;i<li1.size();i++)
{
HashMap hmap = new HashMap();
VendorMonth venmonth=(VendorMonth) li1.get(i);
tempsupname=venmonth.getId().getSupplierName();
if(i==0){
supname=venmonth.getId().getSupplierName();
}
if(!supname.equals(tempsupname)){
obj.put("label", supname);
obj.put("data", jsonarrmast);
jsonarrmast = new JSONArray();
s.add(obj);
finalarray.put(obj);
obj = new JSONObject();
supname=venmonth.getId().getSupplierName();
JSONArray jsonarr = new JSONArray();
String date=venmonth.getId().getYearnam()+"/"+venmonth.getId().getMonthnam()+"/01";
String ss=new String("(new Date("+date+")).getTime()");
jsonarr.put(ss);
jsonarr.put(venmonth.getId().getRentalrate());
jsonarrmast.put(jsonarr);
}
else
{
JSONArray jsonarr = new JSONArray();
String date=venmonth.getId().getYearnam()+"/"+venmonth.getId().getMonthnam()+"/01";
String ss=new String("(new Date("+date+")).getTime()");
jsonarr.put(ss);
jsonarr.put(venmonth.getId().getRentalrate());
jsonarrmast.put(jsonarr);
}
if(i==(li1.size()-1)){
obj.put("label", supname);
obj.put("data", jsonarrmast);
jsonarrmast = new JSONArray();
s.add(obj);
finalarray.put(obj);
}
}
but i'm getting the output as given below
[{"data":[["(new Date(2012/12/01)).getTime()",10976.23],["(new Date(2013/1/01)).getTime()",51213.8200000002],["(new Date(2013/2/01)).getTime()",32172.31],["(new Date(2013/3/01)).getTime()",824.600000000001],["(new Date(2013/4/01)).getTime()",838.000000000001],["(new Date(2013/5/01)).getTime()",755.780000000001],["(new Date(2013/6/01)).getTime()",50877.12]],"label":"Weather Ford"},{"data":[["(new Date(2012/12/01)).getTime()",24368.3],["(new Date(2013/1/01)).getTime()",1968.76]],"label":"Logan Tools"},{"data":[["(new Date(2012/12/01)).getTime()",3425.63],["(new Date(2013/1/01)).getTime()",731.75]],"label":"Pioneer tools"}]
You're not going to be able to create a JSON object that matches your declaration, because that's not a JSON object: it's Javascript code.
Once that Javascript code is ran, however, data will contain an object that can be serialized to JSON, and I'm assuming that's what you're trying to achieve.
What your Java code does is add a String to a BasicDBArray - the fact that it's interpreted as a String should not come as a surprise. By the same token, when you add an int or a boolean, they're added as ints and booleans, not strings.
What you actuall want to put in your BasicDBArray is the value that new Date('2011/12/01').getTime() would return if interpreted as Javascript: the number of milliseconds between 1970/01/01 and 2011/12/01. I'm assuming you can retrieve that through something like venmonth.getId().getDate().getTime(), or however it is you retrieve a Date instance from your venmonth object.
I have two JsonObject having same key but different value.
I want to merge both JsonObject with same key in another JsonObject.
JSONObject a = new JSONObject("{\"data\": [ {\"empId\": 1,\"deptId\": 2},{\"empId\": 3,\"deptId\": 4}]}");
JSONObject b = new JSONObject("{\"data\": [ {\"empId\": 7,\"deptId\": 8},{\"empId\": 9,\"deptId\": 10}]}");
The result should be like this.
{\"data\": [ {\"empId\": 1,\"deptId\": 2},{\"empId\": 3,\"deptId\": 4},{\"empId\": 7,\"deptId\": 8},{\"empId\": 9,\"deptId\": 10}]}
Please Let me know how to do this.
Use JSONArray for store multiple JSONObject. Using this no need to worry to assign key for this JSONObject e.g.
JSONObject a = new JSONObject("{\"data\": [ {\"empId\": 1,\"deptId\": 2},{\"empId\": 3,\"deptId\": 4}]}");
JSONObject b = new JSONObject("{\"data\": [ {\"empId\": 7,\"deptId\": 8},{\"empId\": 9,\"deptId\": 10}]}");
Edit
JSONArray jArr_A= a.getJSONArray("data");
JSONArray jArr= new JSONArray();
for(int i=0;i<jArr_A.length();i++){
jArr.put(jArr_A.getJSONObject(i));
}
Now for another object
jArr_A= b.getJSONArray("data");
for(int i=0;i<jArr_A.length();i++){
jArr.put(jArr_A.getJSONObject(i));
}
now check the length of your jArr object has it double.
JSONObject mainJson = new JSONObject();
mainJson.put("data", jArr);