I need to produce this JSON Object
{
"Soft Drinks": {
"T2": [
{
"name": "Bottled",
"T3": [
{
"name": "Lemon",
"T4": [
{
"leaf": [
{
"name": "500 ML"
}
]
}
]
}
]
}
]
}
}
But i am always ending up with creatint this JSON
{
"Soft Drinks": {
"T2": [
{
"name": "Bottled",
"T3": [
{
"name": "Lemon",
"leaf": [
{
"name": "500 ML"
}
]
}
]
}
]
}
}
The leaf level object should come under different obect that is T4
This is my program
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class BuildJSOn {
public static void main(String[] args) throws JSONException {
JSONObject leaf = new JSONObject().put("name", "500 ML");
JSONObject lemon = new JSONObject().put("name", "Lemon").put("leaf", new JSONArray().put(leaf));
JSONArray t3Array = new JSONArray().put(lemon);
JSONObject bottled = new JSONObject().put("name", "Bottled").put("T3", t3Array);
JSONObject softDrink = new JSONObject().put("T2", new JSONArray().put(bottled));
JSONObject json = new JSONObject().put("Soft Drinks", softDrink);
System.out.println(json);
}
}
Try this:
JSONArray t4Array= new JSONArray();
JSONArray leaf= new JSONArray();
JSONObject newLeaf = new JSONObject().put("name", "500 ML");
leaf.put(newLeaf);
JSONObject t4Obj= new JSONObject().put("leaf",leaf);
t4Array.put(t4Obj);
JSONObject lemon = new JSONObject().put("name", "Lemon").put("T4", t4Array);
JSONArray t3Array = new JSONArray().put(lemon);
JSONObject bottled = new JSONObject().put("name", "Bottled").put("T3", t3Array);
JSONObject softDrink = new JSONObject().put("T2", new JSONArray().put(bottled));
JSONObject json = new JSONObject().put("Soft Drinks", softDrink);
Hope it helps.
According to the JSON structure you require, this is how your code should look.
JSONObject lemon = new JSONObject().put("name", "Lemon");
JSONArray t4 = new JSONArray().put(new JSONObject().put("leaf", new JSONArray().put(leaf)));
lemon.put("T4", t4);
You don't seem to mention T4 anywhere. You don't state what library you're using, or how the library you're using works (I assume you didn't write it yourself if you don't know how to add arrays to it) but I'd guess you need something like you did when adding the earlier arrays:
JSONArray t3Array = new JSONArray().put(lemon).put("T4", new JSONArray().put(leaf));
This doesn't really feel like a particularity nice solution, and that data structure looks a bit bizarre, but you need to add a JSONArray T4 somewhere!
Related
This question already has answers here:
Creating nested JSON object for the following structure in Java using JSONObject? [closed]
(2 answers)
Closed 2 years ago.
Below is my code. I still need to add the "studentInfo" field.
JSONObject jo = new JSONObject();
jo.put("name", "ALEX JAMES");
jo.put("id", "22284666");
jo.put("age","13")
JSON body message to be created:
{
"body": {
"studentInfo": {
"name": "ALEX JAMES",
"id": "22284666",
"age": "13"
}
}
}
you can nest objects
JSONObject studentInfo = new JSONObject();
studentInfo.put("name", "ALEX JAMES");
studentInfo.put("id", "22284666");
studentInfo.put("age","13");
JSONObject body = new JSONObject();
body.put("studentInfo" , studentInfo);
JSONObject wrapper = new JSONObject();
wrapper.put("body" , body);
This standalone example seems to do what you want:
import org.json.JSONObject;
class Main {
public static void main(String[] args) {
JSONObject jo = new JSONObject();
JSONObject body = new JSONObject();
jo.put("body", body);
JSONObject si = new JSONObject();
body.put("studentInfo", si);
si.put("name", "Alex James");
si.put("id", "22284666");
si.put("age", 13);
System.out.println(jo.toString(4));
}
}
Output
{"body": {"studentInfo": {
"name": "Alex James",
"id": "22284666",
"age": 13
}}}
Test it on repl.it.
I have been battling with response from server using retrofit.
I have this json response from server
{
"success": true,
"message": "Your Requests",
"data": {
"requests": [
{
"_id": "5d163a5ed2399f8be6d8d867",
"created": "2019-06-28T16:03:42.463Z",
"pickupCoordinates": [
8.0099,
6.0909
],
"destinationCoordinates": [
9.088788,
3.099403
],
"customerName": "Seun Akinbode",
"pickupAddress": "Lekki",
"destinationAddress": "Ajah",
"accessCode": "3334",
"busPlate": "DD222RR",
"flaName": "Simi",
"flaEmail": "awele#kobo360.com",
"__v": 0
} ]
}
I use below class to parse the json but unfortunately, it couldn't extract the array requests into jsonArray
public ArrayList<RequestModel> getData(String response)
{
Log.d("responseData :", response);
ArrayList<RequestModel> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(response);
JSONArray array = mainObj.getJSONArray("data");
Log.d("The main Array :", array.toString());
RequestModel data;
for(int i = 0;i<array.length();i++)
{
data = new RequestModel();
JSONObject resObj = array.getJSONObject(i);
JSONArray reqArray = resObj.getJSONArray("requests");
for( int j =0;j<reqArray.length();j++) {
JSONObject reqObj = reqArray.getJSONObject(j);
data.setAccessCode(reqObj.getString("accessCode"));
Log.d("Accessecode :", reqObj.getString("accessCode"));
data.setCustomerName(reqObj.getString("customerName"));
Log.d("customerName :", reqObj.getString("customerName"));
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
Logcat is printing the JSONObject but it says at ... data of type org.json.JSONObject cannot be converted to JSONArray
You are trying to extract an array from the data field, while the response contains an object. Perhaps you meant to get the object data, then the array requests from within it.
This could be the problem:
JSONArray array = mainObj.getJSONArray("data");
data is an object as seen in the response, not an array.
I need to send a POST request with json payload, and it's a requirement that the whole project is lightweight, so it's just a simple java project, and I'm using java.net.HttpURLConnection and org.json.JSONObject.
This method compiles my payload:
public static String compileSRF() throws JSONException{
Map<String, Boolean> flags = new HashMap<String, Boolean>();
flags.put("overrideStore", true);
flags.put("matchmaking", true);
JSONObject orchestrationFlags = new JSONObject(flags);
JSONObject requesterSystem = new JSONObject();
JSONObject requestedService = new JSONObject();
requesterSystem.put("systemGroup", "testGroup");
requesterSystem.put("systemName", "testSystem");
requesterSystem.put("address", "localhost");
requestedService.put("serviceGroup", "Temperature");
requestedService.put("serviceDefinition", "IndoorTemperature");
List<String> interfaces = new ArrayList<String>();
interfaces.add("json");
requestedService.put("interfaces", interfaces);
JSONObject payload = new JSONObject();
payload.put("requesterSystem", requesterSystem);
payload.put("requestedService", requestedService);
payload.put("orchestrationFlags", orchestrationFlags);
return payload.toString();
}
The produced payload looks like this:
{
"orchestrationFlags": {
"overrideStore": true,
"matchmaking": true
},
"requesterSystem": {
"address": "localhost",
"systemName": "testSystem",
"systemGroup": "testGroup"
},
"requestedService": {
"interfaces": ["json"],
"serviceGroup": "Temperature",
"serviceDefinition": "IndoorTemperature"
}
}
But when this payload gets to my web server, and the code tries to parse the "orchestrationFlags" hashmap, it does not succeed, and uses default values instead. When I did the testing for the code on the web server, this is the payload structure I've always used in Postman and it worked:
{
"orchestrationFlags": {
"entry": [
{
"key": "overrideStore",
"value": true
},
{
"key": "matchmaking",
"value": true
}
]
},
//requesterSystem and requestedService is the same
}
How can I achive this with JSONObject? (or with another simple API, but maven import is not an option)
Thank you!
Use List<Map<String,Object>> for the entry attribute and put this value in orchestrationFlags json object.
//Refactored code below:
public static String compileSRF() throws JSONException{
List<Map<String,Object>> entryList = new ArrayList<>();
Map<String, Object> flag1 = new HashMap<>();
flag1.put("key", "overrideStore");
flag1.put("value", true);
entryList.add(flag1);
Map<String, Object> flag2 = new HashMap<>();
flag2.put("key", "matchmaking");
flag2.put("value", true);
entryList.add(flag2);
JSONObject orchestrationFlags = new JSONObject();
JSONObject requesterSystem = new JSONObject();
JSONObject requestedService = new JSONObject();
orchestrationFlags.put("entry", entryList);
requesterSystem.put("systemGroup", "testGroup");
requesterSystem.put("systemName", "testSystem");
requesterSystem.put("address", "localhost");
requestedService.put("serviceGroup", "Temperature");
requestedService.put("serviceDefinition", "IndoorTemperature");
List<String> interfaces = new ArrayList<String>();
interfaces.add("json");
requestedService.put("interfaces", interfaces);
JSONObject payload = new JSONObject();
payload.put("requesterSystem", requesterSystem);
payload.put("requestedService", requestedService);
payload.put("orchestrationFlags", orchestrationFlags);
return payload.toString(4);
}
Output:
{
"orchestrationFlags": {"entry": [
{
"value": true,
"key": "overrideStore"
},
{
"value": true,
"key": "matchmaking"
}
]},
"requesterSystem": {
"address": "localhost",
"systemName": "testSystem",
"systemGroup": "testGroup"
},
"requestedService": {
"interfaces": ["json"],
"serviceGroup": "Temperature",
"serviceDefinition": "IndoorTemperature"
}
}
Hope this helps.
I would like to create the following geojson using the simple-json-1.1.1 jar.
{"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "ESPG:4326"
}
},
"features":[
{
"type":"Feature",
"geometry":{
"type":"Point",
"coordinates":[55,55]
},
"properties":{
"desc":"something"}
}
]
}
Any ideas on how to do that?Thanks!!
The code to create the geojson mentioned above is the following:
JSONObject featureCollection = new JSONObject();
featureCollection.put("type", "FeatureCollection");
JSONObject properties = new JSONObject();
properties.put("name", "ESPG:4326");
JSONObject crs = new JSONObject();
crs.put("type", "name");
crs.put("properties", properties);
featureCollection.put("crs", crs);
JSONArray features = new JSONArray();
JSONObject feature = new JSONObject();
feature.put("type", "Feature");
JSONObject geometry = new JSONObject();
JSONAray JSONArrayCoord = new JSONArray();
JSONArrayCoord.add(0, 55);
JSONArrayCoord.add(1, 55);
geometry.put("type", "Point");
geometry.put("coordinates", JSONArrayCoord);
feature.put("geometry", geometry);
features.add(feature);
featureCollection.put("features", features);
My Json are following
{
"q": {
"region": "NYC",
"or": [
{
"duration": "12"
}
]
},
"sort": "recent"
}
How to write in JsonObject.I tried with following code:
JSONObject obj = new JSONObject();
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
JSONObject obj4 = new JSONObject();
try {
obj.put("q", obj1);
obj.put("sort", "recent");
obj1.put("reg", "NYC");
obj2.put("duration", new Integer(12));
obj4.put()
} catch (JSONException e) {
}
I got stuck in creating Array of list. How can I convert into Json Object?
You may build the JSONObject in this way:
public class Test {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("q", new JSONObject()
.put("region", "NYC")
.put("or", new JSONArray()
.put(new JSONObject()
.put("duration","12"))))
.put("sort", "recent");
System.out.println(obj);
}
}
The output:
{"q":{"or":[{"duration":"12"}],"region":"NYC"},"sort":"recent"}