Merging of two JsonObject having same key and different value - java

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);

Related

JsonObject by default adding backslash to json string

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);

Not Finding JSON ARRAY value within the JSON Object in JAVA - ANDROID

I am obtaining a JSON response from an API which contains color information.
This is the response:
enter image description here
I want to be able to access the html_code value from the background_colors array within the info JSON object.
Firstly, have tried doing this simply with this code:
result = stack.getBody().getObject().toString(2);
JSONObject parentObject = new JSONObject(_result);
JSONArray jr = parentObject.getJSONArray("results");
JSONObject jb1 = jr.getJSONObject(0);
System.out.print(jb1);
This prints me out the info Object as expected.
However, if I try and access the JSON Array "background_colors" using this,
JSONObject parentObject = new JSONObject(_result);
JSONArray jr = parentObject.getJSONArray("results");
JSONObject jb1 = jr.getJSONObject(0);
System.out.print(jb1);
JSONArray jsonArray =
jb1.getJSONArray("background_colors");
System.out.print(jsonArray);
I get this error: No value for "background_colors".
I know this error means that the background_colors array does not exist in the JSONObject but I have no idea how and why this would be the case?
Any help would be much appreciated.
background_colors is a property of the info object not the root object from the array.
Try this:
JSONObject parentObject = new JSONObject(_result);
JSONArray jr = parentObject.getJSONArray("results");
JSONObject jb1 = jr.getJSONObject(0).getJSONObject("info");
JSONArray jsonArray = jb1.getJSONArray("background_colors");
System.out.print(jsonArray);
JSONObject jb1 = jr.getJSONObject(0).getJSONObject("info");
JSONArray jsonArray = jb1.getJSONArray("background_colors");

Value as string array in gson key value

I'm new to JSON. I'm trying to assign value (in key value pairs) as array of strings using GSON.
The JSON should look like as below:
{ "name": "path", "value": [ "/my-path" ,"/my-path2","/newpath"] }
How can I achieve this?
Thanks.
Even thoe I will hardly recommend you to use POJOS, gson is flexible enough to allow you to do what you want:
JsonObject jo = new JsonObject();
jo.addProperty("name", "path");
JsonArray jsonArray = new JsonArray();
jsonArray.add("my-path");
jsonArray.add("my-path2");
jsonArray.add("my-new-path");
jo.add("value", jsonArray);
System.out.println(jo);

Merging Two JSONArray inside JSONObject in JAVA

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);

double quotes found in json array

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.

Categories

Resources