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;
Related
How can I extract JSON Array and JSON Object from JSON.
Below is the input:
{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true,
"Fields": [{
"objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"
},
{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"
}]
}
I want JSON Array and JSON Object separately and output should be like:
JSONArray
"Fields":[{ "objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"},{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"}]
and JSON Object should be like:
{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true
}
its pretty simple if you know java JSON API
String jsonString="{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true,
"Fields": [{
"objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"
},
{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"
}]
}"
JSONObject jObject= new JSONObject(jsonString);
JSONObject jo = new JSONObject(); //creating new Jobject
// putting data to JSONObject
jo.put("messageName", jObject.getString("messageName").toString());
jo.put("orgId", jObject.getString("orgId").toString());
jo.put("comment", jObject.getString("comment").toString());
JSONArray Fields= jObject.getJSONArray("Fields");//extract field array
JSONArray ja = new JSONArray(); //creating new json array.
int Arraylength = Fields.length();
for(int i=0;i<Arraylength;i++)
{
Map m = new LinkedHashMap(2);
JSONObject ArrayjObj = Fields.getJSONObject(i);
m.put("objectId", ArrayjObj.getString("objectId").toString());
m.put("fieldId", ArrayjObj.getString("fieldId").toString());
// adding map to list
ja.add(m);
}
JSONObject fieldsObj = new JSONObject();
fieldsObj.put("Fields", ja); // Fields Array Created
for JSON api refer this
you can fetch particular values as per keys into a json object and rest into a separate json array
String strJSON =" {\"id\":\"12\",\"messageName\":\"ReportCard\" , \"Fields\":[{\"objectId\": \"1234-56789-asdv\", \"fieldId\": \"1245-7852-dhjd\"},{\"objectId\": \"1234-56hgjgh789-hjjhj\", \"fieldId\": \"12sdf45-78sfg52-dfjhjd\"}] }";
JSONArray ja = new JSONArray();
JSONObject jo1= new JSONObject();
JSONObject jo= new JSONObject(strJSON);
ja= jo.getJSONArray( "Fields");
jo1.put("messageName",jo.get(messageName));
jo1.put("orgId",jo.get(orgId));
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)
I am using Rest Assured for API testing, how do I send array objects in a POST? For a plain string I know I can do something like this
JSONObject json = new JSONObject();
json.put("firstname", "John"));
json.put("lastname", "James");
request.body(json.toJSONString());
request.post("/my/post/url/end/point");
How do I send an object like this using the JSONObject and Rest Assured?
{
"price": "234",
"phoneNumber": "09022334422",
"owner": [{
"digits": "1122334455",
"myname": "Abisoye Haminat",
"code": "058",
"default": "true"
}]
}
To send an array, you can use JSONArray:
JSONObject jsonObjectToPost = new JSONObject();
JSONArray array = new JSONArray();
JSONObject arrayItem = new JSONObject();
arrayItem.put("code","058");
arrayItem.put("default", "true");
array.put(arrayItem.toString());
jsonObjectToPost.put("owner", array.toString())
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"
}
]
}
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