JsonObject by default adding backslash to json string - java

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

Related

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

Parsing multiple json objects in java

I have this json file that I'm trying to parse in my program.
{
"items": [{
"0": {
"item_name":"Test Item",
"item_rarity":2,
"item_material":"STICK",
"required_level":1,
"min_damage":100.0,
"max_damage":200.0,
"item_set":"The cool kids",
"attributes":[{"name":"lifesteal","modifier":20}]
},
"1": {
"item_name":"Test Item",
"item_rarity":2,
"item_material":"STICK",
"required_level":1,
"min_damage":100.0,
"max_damage":200.0,
"item_set":"The cool kids",
"attributes":[{"name":"lifesteal","modifier":20}]
}
}]
}
I am printing the JSON string, but instead of getting the individual objects (0, then 1, then 2, etc...) it only gets the whole array every time I print it out.
Object obj = jsonParser.parse(new FileReader(new File(ValaCraft.getInstance().getDataFolder() + "/test.json")));
JSONObject jsonObject = (JSONObject) obj;
JSONArray items = (JSONArray) jsonObject.get("items");
for (int i = 0; i < items.size(); i++) {
JSONObject item = (JSONObject) items.get(i);
System.out.print(item.toString());
}
Anybody have an idea on how to parse this file (without GSON, attributes is a custom class and I found it complicated to use the auto parse that gson comes with).
What did you find troubling with GSON?
If you pass it to the gson.fromJSON as a JSONObject class, it should work, and you'll be able to get data from the JSON object.
Gson gson = new Gson();
JsonObject jsonFile = gson.fromJson(file.json, JsonObject.class);
Then you can call
JsonArray array = jsonFile.get("items").getAsJsonArray();
Then to grab the attributes from the first element of the array.
array.get(0).getAsJsonObject().get("attributes").getAsJsonArray();

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.

how to parse a JSON string which is inside a array

I have a json of following format:
{
"Result": {
"question": "Barack Obama vs Mitt Romney?",
"option": [
"Barack Obama",
"Mitt Romney",
"Other"
],
"percentage": [
20,
40,
80
]
}
}
and I am using following code to parse it but this giving null pointer exception at option array.
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONObjectFromUrl(url);
Log.e("json",json.toString());
Log.e("-------url-------", ""+url);
String resultStr = json.getString("Result");
Log.e("result string ",resultStr);
JSONObject jsonObject2 = new JSONObject(resultStr);
String question_string = jsonObject2.getString("question");
Log.e("question String ",question_string);
String option_str = jsonObject2.getString("option");
JSONArray optionArray = new JSONArray(option_str);
Log.d("option array", String.valueOf(optionArray.length()));
You need to get the json array this way:
JSONArray optionArray = jsonObject2.getJSONArray("option");
Log.d("option array", String.valueOf(optionArray.length()));
check http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Use:
JSONArray optionArray = jsonObject2.getJSONArray("option");
as "option" key points to an array and not to a String.
You're going way too complicated here, and not using those lovely GetJSONObject and getJSONArray functions, which will cause you to double parse a lot. Try this
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONObjectFromUrl(url);
Log.e("json",json.toString());
Log.e("-------url-------", ""+url);
JSONObject jsonObject2 = json.getJSONObject("Result");
String question_string = jsonObject2.getString("question");
Log.e("question String ",question_string);
JSONArray optionArray = jsonObject2.getJSONArray("option");
Instead of using
String option_str = jsonObject2.getString("option");
use this :
JSONARRAY optionArray = jsonObject2.getJSONAray("option");
for(int i=0;i<optionArray.length; i++){
String option = optionArray[i].getString();}
Try this..

Merging of two JsonObject having same key and different value

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

Categories

Resources