With the imports org.json.JSONArray and org.json.JSONObject
JSONObject object = new JSONObject();
object.put("name", "sample");
JSONArray array = new JSONArray();
JSONObject arrayElementOne = new JSONObject();
arrayElementOne.put("setId", 1);
JSONArray arrayElementOneArray = new JSONArray();
JSONObject arrayElementOneArrayElementOne = new JSONObject();
arrayElementOneArrayElementOne.put("name", "ABC");
arrayElementOneArrayElementOne.put("type", "STRING");
JSONObject arrayElementOneArrayElementTwo = new JSONObject();
arrayElementOneArrayElementTwo.put("name", "XYZ");
arrayElementOneArrayElementTwo.put("type", "STRING");
arrayElementOneArray.put(arrayElementOneArrayElementOne);
arrayElementOneArray.put(arrayElementOneArrayElementTwo);
arrayElementOne.put("setDef", arrayElementOneArray);
array.put(arrayElementOne);
object.put("def", array);
I did not include first array's second element for clarity. Hope you got the point though.
EDIT:
The previous answer was assuming you were using org.json.JSONObject and org.json.JSONArray.
For net.sf.json.JSONObject and net.sf.json.JSONArray :
JSONObject object = new JSONObject();
object.element("name", "sample");
JSONArray array = new JSONArray();
JSONObject arrayElementOne = new JSONObject();
arrayElementOne.element("setId", 1);
JSONArray arrayElementOneArray = new JSONArray();
JSONObject arrayElementOneArrayElementOne = new JSONObject();
arrayElementOneArrayElementOne.element("name", "ABC");
arrayElementOneArrayElementOne.element("type", "STRING");
JSONObject arrayElementOneArrayElementTwo = new JSONObject();
arrayElementOneArrayElementTwo.element("name", "XYZ");
arrayElementOneArrayElementTwo.element("type", "STRING");
arrayElementOneArray.add(arrayElementOneArrayElementOne);
arrayElementOneArray.add(arrayElementOneArrayElementTwo);
arrayElementOne.element("setDef", arrayElementOneArray);
object.element("def", array);
Basically it's the same, replacing the method 'put' for 'element' in JSONObject, and 'put' for 'add' in JSONArray.
Answer from goten on Stack OverflowWith the imports org.json.JSONArray and org.json.JSONObject
JSONObject object = new JSONObject();
object.put("name", "sample");
JSONArray array = new JSONArray();
JSONObject arrayElementOne = new JSONObject();
arrayElementOne.put("setId", 1);
JSONArray arrayElementOneArray = new JSONArray();
JSONObject arrayElementOneArrayElementOne = new JSONObject();
arrayElementOneArrayElementOne.put("name", "ABC");
arrayElementOneArrayElementOne.put("type", "STRING");
JSONObject arrayElementOneArrayElementTwo = new JSONObject();
arrayElementOneArrayElementTwo.put("name", "XYZ");
arrayElementOneArrayElementTwo.put("type", "STRING");
arrayElementOneArray.put(arrayElementOneArrayElementOne);
arrayElementOneArray.put(arrayElementOneArrayElementTwo);
arrayElementOne.put("setDef", arrayElementOneArray);
array.put(arrayElementOne);
object.put("def", array);
I did not include first array's second element for clarity. Hope you got the point though.
EDIT:
The previous answer was assuming you were using org.json.JSONObject and org.json.JSONArray.
For net.sf.json.JSONObject and net.sf.json.JSONArray :
JSONObject object = new JSONObject();
object.element("name", "sample");
JSONArray array = new JSONArray();
JSONObject arrayElementOne = new JSONObject();
arrayElementOne.element("setId", 1);
JSONArray arrayElementOneArray = new JSONArray();
JSONObject arrayElementOneArrayElementOne = new JSONObject();
arrayElementOneArrayElementOne.element("name", "ABC");
arrayElementOneArrayElementOne.element("type", "STRING");
JSONObject arrayElementOneArrayElementTwo = new JSONObject();
arrayElementOneArrayElementTwo.element("name", "XYZ");
arrayElementOneArrayElementTwo.element("type", "STRING");
arrayElementOneArray.add(arrayElementOneArrayElementOne);
arrayElementOneArray.add(arrayElementOneArrayElementTwo);
arrayElementOne.element("setDef", arrayElementOneArray);
object.element("def", array);
Basically it's the same, replacing the method 'put' for 'element' in JSONObject, and 'put' for 'add' in JSONArray.
Here is one crude example. You should be able to refine. (You may be interested in this Java "tutorial" http://docs.oracle.com/javaee/7/tutorial/doc/jsonp.htm#GLRBB
(This example uses the JSON reference implementation included in Java EE (and available here: https://java.net/projects/jsonp/downloads/directory/ri)
package com.demo;
import java.io.FileWriter;
import java.io.IOException;
import javax.json.Json;
import javax.json.stream.JsonGenerator;
public class JSONExample {
public static void main(String[] args) {
FileWriter writer = null;
try {
writer = new FileWriter("C:\\Users\\Joseph White\\Downloads\\jsontext.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonGenerator gen = Json.createGenerator(writer);
gen.writeStartObject().write("name", "sample")
.writeStartArray("def")
.writeStartObject().write("setId", 1)
.writeStartArray("setDef")
.writeStartObject().write("name", "ABC").write("type", "STRING")
.writeEnd()
.writeStartObject().write("name", "XYZ").write("type", "STRING")
.writeEnd()
.writeEnd()
.writeEnd()
.writeStartObject().write("setId", 2)
.writeStartArray("setDef")
.writeStartObject().write("name", "abc").write("type", "STRING")
.writeEnd()
.writeStartObject().write("name", "xyz").write("type", "STRING")
.writeEnd()
.writeEnd()
.writeEnd()
.writeEnd()
.writeEnd();
gen.close();
}
}
Parsing a JSON object with nested dynamic values (with known keys)
java - How to access nested elements of json object using getJSONArray method - Stack Overflow
java - How to create a nested JSONObject - Stack Overflow
java - Retrieving values from nested JSON Object - Stack Overflow
Videos
In a problem I am working on, I have an endpoint where I will need to receive a JSON object which have a key that might contain different objects depending on the call. The list of possible objects is known in advance, but I am struggling with how best to model it. Splitting the endpoint into multiple is not an option.
The example looks something like this:
outerObject {
...,
key: object1 | object2 | object3
}
object1 {
"a": "a"
"b": "b"
}
object2 {
"c": 2
"d": "d"
}
object3 {
"e": 3,
"f": 4
}If I was writing it in Rust I would use an `enum` with structs for each of the different objects. This is for Java 21, so using sealed types is not yet an option (I might be able to upgrade, but I am not sure if the different
Using either Jackson or Gson I was think of representing it in one of their Json structures and then determining which object fits when the call is made.
Is this the best option or are there any more generic solutions?
You have to decompose the full object to reach the entry array.
Assuming REPONSE_JSON_OBJECT is already a parsed JSONObject.
REPONSE_JSON_OBJECT.getJSONObject("result")
.getJSONObject("map")
.getJSONArray("entry");
Try this code using Gson library and get the things done.
Gson gson = new GsonBuilder().create();
JsonObject job = gson.fromJson(JsonString, JsonObject.class);
JsonElement entry=job.getAsJsonObject("results").getAsJsonObject("map").getAsJsonArray("entry");
String str = entry.toString();
System.out.println(str);
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.
Maybe you're not using the latest version of a JSON for Java Library.
json-simple has not been updated for a long time, while JSON-Java was updated 2 month ago.
JSON-Java can be found on GitHub, here is the link to its repo: https://github.com/douglascrockford/JSON-java
After switching the library, you can refer to my sample code down below:
public static void main(String[] args) {
String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
JSONObject jsonObject = new JSONObject(JSON);
JSONObject getSth = jsonObject.getJSONObject("LanguageLevels");
Object level = getSth.get("2");
System.out.println(level);
}
And as JSON-Java open-sourced, you can read the code and its document, they will guide you through.
Hope that it helps.
You will have to iterate step by step into nested JSON.
for e.g a JSON received from Google geocoding api
{
"results" : [
{
"address_components" : [
{
"long_name" : "Bhopal",
"short_name" : "Bhopal",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Bhopal",
"short_name" : "Bhopal",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Madhya Pradesh",
"short_name" : "MP",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Bhopal, Madhya Pradesh, India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 23.3326697,
"lng" : 77.5748062
},
"southwest" : {
"lat" : 23.0661497,
"lng" : 77.2369767
}
},
"location" : {
"lat" : 23.2599333,
"lng" : 77.412615
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 23.3326697,
"lng" : 77.5748062
},
"southwest" : {
"lat" : 23.0661497,
"lng" : 77.2369767
}
}
},
"place_id" : "ChIJvY_Wj49CfDkR-NRy1RZXFQI",
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
I shall iterate in below given fashion to "location" : { "lat" : 23.2599333, "lng" : 77.412615
//recieve JSON in json object
JSONObject json = new JSONObject(output.toString());
JSONArray result = json.getJSONArray("results");
JSONObject result1 = result.getJSONObject(0);
JSONObject geometry = result1.getJSONObject("geometry");
JSONObject locat = geometry.getJSONObject("location");
//"iterate onto level of location";
double lat = locat.getDouble("lat");
double lng = locat.getDouble("lng");
You need to create a JSON, and add that JSON as a parameter in your POST. To do that you should probably :
post.add(new BasicNameValuePair("data",json.toString());
You could use org.json.JSONObject, it is included in the Android SDK.
Create a Model Class for the Json, initialize it with your data. Then use Google Gson to convert it toJson also from Json to Back to the Object. and also here are two links which make your life more Easier for using Json. Online Json Editor. You can check that generated json is in the correct format or not. http://www.jsoneditoronline.org/ And Json to POJO Generated (Model Class Generator) http://www.jsonschema2pojo.org/