I'm trying to create a Gson object which will contain differents categories and entries
Here is the sample i'm trying to do:
JsonObject jo = new JsonObject();
JsonArray ja = new JsonArray();
JsonObject mainObj = new JsonObject();
jo.addProperty("firstName", "John");
jo.addProperty("lastName", "Doe");
ja.add(jo);
mainObj.add("employees", ja);
jo = new JsonObject();
ja = new JsonArray();
jo.addProperty("firstName", "jean");
jo.addProperty("lastName", "dorian");
ja.add(jo);
mainObj.add("employees", ja);
jo = new JsonObject();
ja = new JsonArray();
jo.addProperty("firstName", "toto");
jo.addProperty("lastName", "tata");
ja.add(jo);
mainObj.add("manager", ja);
The problem is has you can see I have to create every time a new JSonObject and Array which is I believe not the best practice and also the old value in "employees" is replacing by the second.
Someone can help me on this please?
Br,
Jérémie
I have to create every time a new JSonObject and Array which is I
believe not the best practice
I think it's perfectly fine to do it like this.
and also the old value in "employees" is replacing by the second
The problem is that you want to add a mapping "employees" -> JsonArray two times in your JsonObject. While online JSON parsers such as JSONLint don't say anything about that, it's actually not recommended to have two identical keys in a JsonObject.
This is explained in the RFC 7159, chapter 4:
An object whose names are all unique is interoperable in the sense
that all software implementations receiving that object will agree on
the name-value mappings. When the names within an object are not
unique, the behavior of software that receives such an object is
unpredictable. Many implementations report the last name/value pair
only. Other implementations report an error or fail to parse the
object, and some implementations report all of the name/value pairs,
including duplicates.
Under the hood, the JsonObject structure is implemented with a LinkedTreeMap to save the mappings. When you add a new mapping, the put method is called, which will erase the previous mapped value, if any.
90 #Override public V put(K key, V value) {
91 if (key == null) {
92 throw new NullPointerException("key == null");
93 }
94 Node<K, V> created = find(key, true);
95 V result = created.value;
96 created.value = value;
97 return result;
98 }
If you want to add another Employee to the array, you shouldn't add it directly to the JsonObject and create a new JsonArray.
JsonObject jo = new JsonObject();
JsonArray ja = new JsonArray();
JsonObject mainObj = new JsonObject();
jo.addProperty("firstName", "John");
jo.addProperty("lastName", "Doe");
ja.add(jo);
//remove this line
mainObj.add("employees", ja);
jo = new JsonObject();
//and remove this line
ja = new JsonArray();
jo.addProperty("firstName", "jean");
jo.addProperty("lastName", "dorian");
ja.add(jo);
mainObj.add("employees", ja);
jo = new JsonObject();
ja = new JsonArray();
jo.addProperty("firstName", "toto");
jo.addProperty("lastName", "tata");
ja.add(jo);
mainObj.add("manager", ja);
which will result in:
{
"employees": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "jean",
"lastName": "dorian"
}
],
"manager": [
{
"firstName": "toto",
"lastName": "tata"
}
]
}
Related
I'm just getting started with using json with java. I'm not sure how to access string values within a JSONArray. For instance, my json looks like this:
{
"locations": {
"record": [
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501
"loc": "NEW YORK STATE"
}
]
}
}
my code:
JSONObject req = new JSONObject(join(loadStrings(data.json),""));
JSONObject locs = req.getJSONObject("locations");
JSONArray recs = locs.getJSONArray("record");
I have access to the "record" JSONArray at this point, but am unsure as to how I'd get the "id" and "loc" values within a for loop. Sorry if this description isn't too clear, I'm a bit new to programming.
Have you tried using JSONArray.getJSONObject(int), and JSONArray.length() to create your for-loop:
for (int i = 0; i < recs.length(); ++i) {
JSONObject rec = recs.getJSONObject(i);
int id = rec.getInt("id");
String loc = rec.getString("loc");
// ...
}
An org.json.JSONArray is not iterable.
Here's how I process elements in a net.sf.json.JSONArray:
JSONArray lineItems = jsonObject.getJSONArray("lineItems");
for (Object o : lineItems) {
JSONObject jsonLineItem = (JSONObject) o;
String key = jsonLineItem.getString("key");
String value = jsonLineItem.getString("value");
...
}
Works great... :)
Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray with java8 Stream API.
import org.json.JSONArray;
import org.json.JSONObject;
#Test
public void access_org_JsonArray() {
//Given: array
JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
new HashMap() {{
put("a", 100);
put("b", 200);
}}
),
new JSONObject(
new HashMap() {{
put("a", 300);
put("b", 400);
}}
)));
//Then: convert to List<JSONObject>
List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.collect(Collectors.toList());
// you can access the array elements now
jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
// prints 100, 300
}
If the iteration is only one time, (no need to .collect)
IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.forEach(item -> {
System.out.println(item);
});
By looking at your code, I sense you are using JSONLIB. If that was the case, look at the following snippet to convert json array to java array..
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );
jsonConfig.setRootClass( Integer.TYPE );
int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );
In case it helps someone else,
I was able to convert to an array by doing something like this,
JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()
...or you should be able to get the length
((JSONArray) myJsonArray).toArray().length
HashMap regs = (HashMap) parser.parse(stringjson);
(String)((HashMap)regs.get("firstlevelkey")).get("secondlevelkey");
i have these three json objects :
object = [{name: "Mary", car: "Fiat"}];
owner= [{firstName: "Mack", lastName: "jack"},{firstName: "Steve", lastName:
"martin"}];
children= [{firstName: "toto", lastName: "jack"},{firstName: "titi", lastName:
"martin"}];
I'm using JAVA, what i want to do is merge the three objects to get one object like this :
[{"name": "Mary", "car": "Fiat",
"owner":[{"firstName": "Mack", "lastName": "jack"},{"firstName":
"Steve","lastName": "martin"}],
"children":[{"firstName": "toto", "lastName": "jack"},{"firstName": "titi",
"lastName": "martin"}]
}]
any help please !
you need to read your json file and create a new one with changes in the new JSON structure, i will suppose that you already know how to extract data from a JSON file and i will leave this code example here showing how you can use JSON.Arrays for your purpose.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class jsonClass {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray1 = new JSONArray();
JSONObject jsonTempObject1 = new JSONObject();
jsonTempObject1.put("name","Mary");
jsonTempObject1.put("car","Fiat");
jsonArray1.add(jsonTempObject1);
JSONArray jsonArray2 = new JSONArray();
JSONObject jsonTempObject2 = new JSONObject();
jsonTempObject2.put("firstName","Mack");
jsonTempObject2.put("lastName","Jack");
jsonArray2.add(jsonTempObject2);
jsonObject.put("object", jsonArray1);
jsonObject.put("owner", jsonArray2);
System.out.println(jsonObject.toString());
}
}
You will have the following result:
{
"owner":[{"firstName":"Mack","lastName":"Jack"}],
"object":[{"car":"Fiat","name":"Mary"}]
}
Use following code
JSONObject Obj1 = (JSONObject) jso1.get("Object1");
JSONObject Obj2 = (JSONObject) jso2.get("Object2");
JSONObject combined = new JSONObject();
combined.put("Object1", Obj1);
combined.put("Object2", Obj2)
how can I create a JSON Object like the following, in Java using JSONObject ?
{
"employees": [
{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}
],
"manager": [
{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}
]
}
I've found a lot of example, but not my exactly JSONArray string.
Here is some code using java 6 to get you started:
JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");
JSONArray ja = new JSONArray();
ja.put(jo);
JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);
Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.
An example of this using the builder pattern in java 7 looks something like this:
JsonObject jo = Json.createObjectBuilder()
.add("employees", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Doe")))
.build();
I suppose you're getting this JSON from a server or a file, and you want to create a JSONArray object out of it.
String strJSON = ""; // your string goes here
JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue();
// once you get the array, you may check items like
JSONOBject jObject = jArray.getJSONObject(0);
Hope this helps :)
Small reusable method can be written for creating person json object to avoid duplicate code
JSONObject getPerson(String firstName, String lastName){
JSONObject person = new JSONObject();
person .put("firstName", firstName);
person .put("lastName", lastName);
return person ;
}
public JSONObject getJsonResponse(){
JSONArray employees = new JSONArray();
employees.put(getPerson("John","Doe"));
employees.put(getPerson("Anna","Smith"));
employees.put(getPerson("Peter","Jones"));
JSONArray managers = new JSONArray();
managers.put(getPerson("John","Doe"));
managers.put(getPerson("Anna","Smith"));
managers.put(getPerson("Peter","Jones"));
JSONObject response= new JSONObject();
response.put("employees", employees );
response.put("manager", managers );
return response;
}
Please try this ... hope it helps
JSONObject jsonObj1=null;
JSONObject jsonObj2=null;
JSONArray array=new JSONArray();
JSONArray array2=new JSONArray();
jsonObj1=new JSONObject();
jsonObj2=new JSONObject();
array.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));
array2.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));
jsonObj1.put("employees", array);
jsonObj1.put("manager", array2);
Response response = null;
response = Response.status(Status.OK).entity(jsonObj1.toString()).build();
return response;
I need to prepare a json file with this format:
[{x: "0", y: a},{x: "1", y: b},{x: "2", y: c}]
I implemented the following technique with JSONObjects and JSONArray:
JSONArray ac=new JSONArray();
JSONObject acontent=new JSONObject();
acontent.put("x", "0");
acontent.put("y",a);
acontent.put("x", "1");
acontent.put("y",b);
acontent.put("x", "2");
acontent.put("y",c);
ac.add(acontent);
However I could only get this output,[{x: "2", y: c}]. How can I retain all the previous values of x and y?
There are far more elegant solutions than this, but the general idea is that you need 1 object for each element in the original array.
JSONArray ac=new JSONArray();
JSONObject acontent=new JSONObject();
acontent.put("x", "0");
acontent.put("y",a);
ac.add(acontent);
acontent = new JSONObject();
acontent.put("x", "1");
acontent.put("y",b);
ac.add(acontent);
acontent = new JSONObject();
acontent.put("x", "2");
acontent.put("y",c);
ac.add(acontent);
I have the following Json and I want to parse the array (cars) ,
[
{
"name": "John",
"city": "Berlin",
"cars": [
"audi",
"bmw"
],
when i tried with the following code i got error
JSONParser parser = new JSONParser();
JSONArray a = (JSONArray) parser.parse(new FileReader(
"C:\\General\\Json\\json.txt"));
for (Object o : a) {
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
}
here is the error "jsonObject cannot be resolved"
how should i overcome it?
JSONArray cars = (JSONArray) jsonObject.get("cars");
you did not declared jsonObject
JSONArray cars = (JSONArray) person.get("cars"); try this instead of JSONArray cars = (JSONArray) jsonObject.get("cars"); this PSR also correct