How to extract JSONArray and JSONObject from a JSON in Java - java

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

Related

Get the keys from JSON Array into a list without Jackson

I have an service that returns me an json object like the below
{
"header": {},
"title": {},
"terms": {
"data": {
"list": [
"string": 1,
"string1": 2,
"string2": 3
]
}
}
}
Now I need to get the keys of the list json array into a list. I have got the array into an object
List<String> allTerms = new ArrayList<String>();
String response = HttpRequest.get("http://myservice/get").body();
JSONParser parser = new JSONParser();
Object obj = parser.parse(response);
JSONObject jsonObject = (JSONObject) obj;
JSONObject fieldObj = (JSONObject)jsonObject.get("terms");
JSONObject queryObj = (JSONObject)fieldObj.get("data");
JSONArray termsArr = (JSONArray) queryObj.get("list");
//iterate the termsarr and get the string,string1,string2 keys alone to allTerms list
Is there a more better way to do this? Im using json-simple and a custom http client
By using basic for loop
for(int i=0; i<termsArr.length(); i++) {
String[] arr = termsArr.getString(i).split("\"");
allTerms.add(arr[1]);
}

Parsing json error: java.lang.IllegalStateException: Not a JSON Object:

I am trying to parse a large json file which contains a bunch of cities (the following is the first two cities in the file):
[
{
"id": 707860,
"name": "Hurzuf",
"country": "UA",
"coord": {
"lon": 34.283333,
"lat": 44.549999
}
},
{
"id": 519188,
"name": "Novinki",
"country": "RU",
"coord": {
"lon": 37.666668,
"lat": 55.683334
}
} ]
I want to get the IDs of cities whose "name" value matches a String:
JsonParser parser = new JsonParser();
JsonElement jsontree = parser.parse(new FileReader("C:/Users/kevin/Eclipse-workspace-new/kevinzhou_CSCI201_assignment3/WebContent/city.list.json"));
JsonElement je = jsontree.getAsJsonObject();
JsonArray ja = je.getAsJsonArray();
for (Object o : ja)
{
JsonObject city = (JsonObject) o;
if(cityName == city.get("name").getAsString())
{
System.out.println(city.get("id").getAsString());
}
}
However, I am getting the following error : java.lang.IllegalStateException: Not a JSON Object:
and then it spits out the entire file after the colon.
change to
// JsonElement je = jsontree.getAsJsonObject();
JsonArray ja = jsontree.getAsJsonArray();
as it contains an Array at the top level
Try below given code to handle both condition
if (jsontree instanceof JsonObject) {
JsonObject jobject = new JsonObject(jsontree .getAsJsonObject());
} else if (jsontree instanceof JsonArray) {
JsonArray jarray = new JsonArray(jsontree .getAsJsonArray());
}

How to parse this json in android studio?

{
"result_count": 251175,
"images": [
{
"id": "649682800",
"display_sizes": [
{
"is_watermarked": false,
"name": "thumb",
"uri": "https://media.gettyimages.com/photos/sergi-roberto-of-barcelona-celebrates-as-he-scores-their-sixth-goal-picture-id649682800?b=1&k=6&m=649682800&s=170x170&h=UjuhQ2k4pOnhCh5a1oLuC4t5rwX8332a-PEqZ8dpUfY="
}
],
"referral_destinations": [
{
"site_name": "gettyimages",
"uri": "https://www.gettyimages.com/detail/news-photo/sergi-roberto-of-barcelona-celebrates-as-he-scores-their-news-photo/649682800"
}
],
"title": "FC Barcelona v Paris Saint-Germain - UEFA Champions League Round of 16: Second Leg"
}
The above JSON Data is missing ] } . So make the data a valid JSON by adding ] } at the end
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.optJSONArray("images");
for(int i=0; i< jsonArray.length(); i++)
{
JSONObject jsonObjec = jsonArray.optJSONObject(i);
jsonObjec.optString("id");
jsonObjec.optString("title");
JSONArray display_sizes = jsonObjec.optJSONArray("display_sizes");
// get the display_sizes Array details
JSONArray referral_destinations = jsonObjec.optJSONArray("referral_destinations");
// get the referral_destinations Array details
}
First it is invalid json.
Try using gson library to parse the json.
Try this link
gson library to parse json

Posting array object in JSON body

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

Add new content to JSON-File

i have a json-file called "user.json". Now i want to add a new user. I know how to get the content of the file and put it in a String, but i dont know how to add new content correctly. "jsonString" is the content of "user.json"
JSONParser parser = new JSONParser();
Object object = parser.parse(jsonString);
JSONObject jsonObject = (JSONObject) object;
jsonObject.put("name", name);
jsonObject.put("region", region);
jsonObject.put("v1", v1);
jsonObject.put("v2", v2);
System.out.println(jsonObject.toJSONString());
The output is:
{
"v1": false,
"v2": false,
"name": "test",
"region": "",
"user": [
{
"v1": "true",
"v2": "true",
"name": "UserName",
"region": ""
}
]
}
But it should be:
{
"user": [
{
"v1": "true",
"v2": "true",
"name": "UserName",
"region": ""
},
{
"v1": false,
"v2": false,
"name": "test",
"region": ""
}
]
}
Does somebody know how to do it right?
I looked it up but all the examples are not working for me, because when i try
JSONObject object = new JSONObject(jsonString);
or
JSONArray array = new JSONArray(jsonString);
i always get "the constructor ist undefined".
Edit:
content of user.json
{"user":[
{"name":"Testuser1", "region":"A", "v1":"false", "v2":"false"},
{"name":"Testuser2", "region":"B", "v1":"true", "v2":"true"},
{"name":"Testuser3", "region":"B", "v1":"false", "v2":"false"},
{"name":"Testuser4", "region":"A", "v1":"true", "v2":"true"},
{"name":"Testuser5", "region":"A", "v1":"false", "v2":"false"}
]}
Edit2:
I solved the problem
Object object = parser.parse(new FileReader(classLoader.getResource("user.json").getFile()));
JSONObject jsonObject = (JSONObject) object;
JSONArray array = (JSONArray) jsonObject.get("user");
JSONObject newObject = new JSONObject();
newObject.put("name", name);
newObject.put("region", region);
newObject.put("v1", v1);
newObject.put("v2", v2);
array.add(newObject);
Map<String, JSONArray> map = new HashMap<>();
map.put("\"user\"", array);
String mapInhalt = map.toString();
if (mapInhalt.contains("=")) {
System.out.println("yop");
mapInhalt.replaceFirst("=", ":");
}
System.out.println(mapInhalt);
it seems you are adding fields to your jsonObject, and what you want to do it basically adding the new object to the inner json array (in this case field is called "user"
try this:
JSONObject newObject=new JSONObject();
newObject.put("name", name);
newObject.put("region", region);
newObject.put("v1", v1);
newObject.put("v2", v2);
jsonObject.getJSONArray("user").add(newObject)
you can use fromObject() method:
JSONObject json = JSONObject.fromObject(jsonStr);
JSONArray jsonArry = JSONArray.fromObject(jsonStr);

Categories

Resources