Add List<String> to the JSONArray - java

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"]

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

How to combine two or more JSON objects into one JSONObject

I've two JSON Objects as below
firstJSON: {"200":"success"}
secondJSON: {"401":"not found"}
I need to combine them as {"codes":{"200":"success"},{"401":"not found"}} using java.
I tried in 3 ways but couldn't achieve the desired output. Could you please help with code snippet?
code which I've tried as below
JSONObject firstJSON = new JSONObject();
firstJSON.put("200", "success");
String firstJSONStr = firstJSON.toString();
System.out.println("firstJSONStr--> " + firstJSONStr);
JSONObject secondJSON = new JSONObject();
secondJSON.put("401", "not found");
String secondJSONStr = secondJSON.toString();
System.out.println("secondJSONStr--> "+secondJSONStr);
String finalJSONStr = firstJSONStr + "," + secondJSONStr;
JSONObject finalJSON1 = new JSONObject();
finalJSON1.put("codes", new JSONObject(finalJSONStr));
System.out.println("finalJSON1--> " + finalJSON1.toString());
JSONObject finalJSON2 = new JSONObject();
finalJSON2.put("codes", finalJSONStr);
System.out.println("finalJSON2--> " + finalJSON2.toString());
JSONObject finalJSON3 = new JSONObject();
ArrayList<JSONObject> jsonArray = new ArrayList<JSONObject>();
jsonArray.add(firstJSON);
jsonArray.add(secondJSON);
finalJSON3.put("codes", jsonArray);
System.out.println("finalJSON3--> " + finalJSON3.toString());
Output:
firstJSONStr--> {"200":"success"}
secondJSONStr--> {"401":"not found"}
finalJSON1--> {"codes":{"200":"success"}}
finalJSON2--> {"codes":"{\"200\":\"success\"},{\"401\":\"not found\"}"}
finalJSON3--> {"codes":[{"200":"success"},{"401":"not found"}]}
Your expected JSON {"codes":{"200":"success"},{"401":"not found"}} is invalid. You can verify it with https://jsonlint.com/ which will produce an error:
Error: Parse error on line 4:
...00": "success" }, { "401": "not foun
---------------------^
Expecting 'STRING', got '{'
You most likely want an array to group the first and second object which results in below JSON (do notice the square brackets [ and ]):
{"codes":[{"200":"success"},{"401":"not found"}]}
This can be achieved with:
JSONObject first = new JSONObject();
first.put("200", "success");
JSONObject second = new JSONObject();
second.put("401", "not found");
JSONArray codes = new JSONArray();
codes.put(first);
codes.put(second);
JSONObject root = new JSONObject();
root.put("codes", codes);
System.out.println(root);
Got the logic finally.
JSONObject successJSON = new JSONObject();
successJSON.put("description", "success");
JSONObject scJSON = new JSONObject();
scJSON.put("200", successJSON);
JSONObject failJSON = new JSONObject();
failJSON.put("description","failure");
scJSON.put("401", failJSON);
JSONObject finalJSON = new JSONObject();
finalJSON.put("codes", scJSON);
System.out.println("finalJSON --> "+finalJSON.toString());

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

How to merge JsonObjects using JAVA which uses javax.json;

I have these two JsonObject which uses javax.json. How can i merge these three and have as one Jason Object or JsonArray. Please not that I tried JASONObject and it didnt work as it is org. lib.
JsonObject jo = Json.createObjectBuilder()
.add("click", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("object", "Doe")))
.build();
JsonObject jo1 = Json.createObjectBuilder()
.add("open", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("page", "Doe")
.add("ms", "5000")))
.build();
JsonObject jo2 = Json.createObjectBuilder()
.add("open", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("page", "Doe")
.add("ms", "5000")))
.build();
Instead of writing org.json library, I ended up writing a utility method of my own as below
Reference : Merge 2 javax.json.JsonObject
private JsonObject mergeProfileSummary(JsonObject oldJsonObject, JsonObject newJsonObject) {
JsonObjectBuilder jsonObjectBuilder =Json.createObjectBuilder();
for (String key : oldJsonObject.keySet()){
jsonObjectBuilder.add(key, oldJsonObject.get(key));
}
for (String key : newJsonObject.keySet()){
jsonObjectBuilder.add(key, newJsonObject.get(key));
}
return jsonObjectBuilder.build();
}
Try this,
JSONObject mergeJson = new JSONObject();
mergeJson.putAll(jo1);
mergeJson.putAll(jo2);
mergeJson.putAll(jo3);
I changed the creating JASONObject part by using org.json lib and it worked;
JSONObject jo = new JSONObject();
jo.put("page", "some val");
jo.put("ms", time);
JSONObject finalObj = new JSONObject();
finalObj.put("open", jo);
JSONObject jo1 = new JSONObject();
jo.put("object", ele.getAttributes().getNamedItem("seleniumwebdriver").getNodeValue());
JSONObject finalObj = new JSONObject();
finalObj.put("click", jo);
And here is the code for merging:
JSONObject finalArr = new JSONObject();
finalJsonArr.add(jo);
finalJsonArr.add(jo1);

Multiple values for a JSON key

I am a beginner on JSON in Java http://json.org/java/
How can I create a JSON object like this?
{
"RECORD": {
"customer_name": "ABC",
"customer_type": "music"
}
}
Try like this:
JSONObject jsonObject = new JSONObject();
jsonObject.put("customer_name", "ABC");
jsonObject.put("customer_type", "music");
JSONObject jsonObject_rec = new JSONObject();
jsonObject_rec.put("RECORD", jsonObject);
System.out.println(jsonObject_rec);
You have to make "RECORD" an JSONobject. This is an example:
JSONObject json = new JSONObject();
// Add a JSON Object
JSONObject Record = new JSONObject();
Record.put( "customer_name", "ABC");
Record.put( "customer_type", "music");
json.put( "RECORD", Record);
// P toString()
System.out.println( "JSON: " + json.toString() );

Categories

Resources