How to add element to json data - java

I have a json something like this below .I want to read it and add 2 more attribute ti it like country and state
[
{
"id": "123",
"testname": "test123",
"name": "John Doe",
"active": true,
"type": "test6"
}
{
"id": "456",
"testname": "test564",
"name": "Ship Therasus",
"active": true,
"type": "test7"
}
]
Resulting json
[
{
"id": "123",
"testname": "test123",
"name": "John Doe",
"active": true,
"type": "test6",
"country":"USA",
"state":"KA"
}
{
"id": "456",
"testname": "test564",
"name": "Ship Therasus",
"active": true,
"type": "test7",
"country":"UK",
"state":"MA"
}
]
I am doing something like this I tried JSONObject but no output.
JSONArray xmlJSONObj2 = new JSONArray(output);
System.out.println("Output from Server .... \n"+xmlJSONObj2.get(0));

you can use for loop to iterate over JSONArray, Once you have jsonObject use put for extra attribute like this
for(int i=0;i<jsonArray.length();i++){
JSONObject json = jsonArray.getJSONObject(i);
// do this for all remaining field
if(json.has("id")){
String id = json.get("id").toString();
}
// finally put extra attributes to that jsonobject
json.put("country", "USA");
json.put("state", "KA")
}

missed commas after "type":"test6"
{
"id": "123",
"testname": "test123",
"name": "John Doe",
"active": true,
"type": "test6" <------
"country":"USA",
"state":"KA"
}

Related

I need to send the request correctly, but I don't know how to get the required values from objects

How to get a new list from the list of objects?
I need a new list of objects to POST request
this list of objects i get from response:
{
"success": true,
"body": {
"users": [
{
"type": "unknown",
"data": [
{
"id": "8",
"firstName": "Jackson",
"lastName": "Baker",
"group": "false"
},
{
"id": "11",
"firstName": "Charlotte",
"lastName": "Garcia",
"group": "false"
},
{
"id": "7",
"firstName": "Henry",
"lastName": "Thompson",
"group": "false"
},
{
"id": "24",
"firstName": "Elijah",
"lastName": "Miller",
"group": "false"
}
]
}
]
}
}
I need to form a new object from response:
{
"success": true,
"body": {
"users": [
{
"type": "unknown",
"data": [
{
"id": "8",
"group": "false"
},
{
"id": "11",
"group": "false"
},
{
"id": "7",
"group": "false"
},
{
"id": "24",
"group": "false"
}
]
}
]
}
}
This new list of object I need to post a request.
I have a JSON Schema, but i don't know how i can make this structure.
My problem is that I can't get the values from fields. I'm using the path "body.users.data.find {it.id} .id" but it finds the id array but I need a users list with values from two fields.
As the users node and data node are all list type, you need use two loop:
import groovy.json.JsonSlurper
// text is your json response text
def result = new JsonSlurper().parseText(text)
result.body.users.each{it.data.each{it.remove("firstName");it.remove("lastName")}}
// result is the what you wanted
println(result)

How to do Parsing JSON string in Java with nested arrays

Starting from the similar question,
Nested JSON Array in Java
I have a somewhat odd json as a response from a REST api(POST) call. I need to find out the id and name of the sub_items array in each items array element.
I tried like given below for which I am getting error like
org.json.JSONException: JSONObject["items.sub_items"] not found.
I also tried just 'sub_items' as the parameter also, but no. I am using GSON. No choice use others.
final JSONObject jsonObj = new JSONObject(JSON_STRING);
final JSONArray subItems = jsonObj.getJSONArray("items.sub_items");
final int n = subItems.length();
for (int i = 0; i < n; ++i) {
final JSONObject subI= subItems.getJSONObject(i);
System.out.println("id="+subI.getString("id"));
System.out.println("name="+subI.getString("name"));
}
The following is my json as a response from a REST api call.
{
"menu": {
"items": [{
"id": 1,
"code": "hot1_sub1_mnu",
"name": "Mutton",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Mutton Pepper Fry",
"price": "100"
}, {
"id": "02",
"name": "Mutton Curry",
"price": "100"
}]
},
{
"id": "2",
"code": "hot1_sub2_mnu",
"name": "Sea Food",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Fish Fry",
"price": "150"
}]
},
{
"id": "3",
"code": "hot1_sub3_mnu",
"name": "Noodles",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Chicken Noodles",
"price": "70"
}, {
"id": "02",
"name": "Egg Noodles",
"price": "60"
}]
}
]
}}
As I said, my JSON is a response from an REST api call, and it is 7300 lines long, like shown below with the outline, as shown in code beautifier.
object {3}
infoTransferReqResp {1}
paramExtens : null
pageGroups {1}
pageGroups [1]
0 {4}
page_group_name : LFG - LG - Insured Summary
page_group_id : 8100
**pages [3]**
repeatingBlocks {1}
I needed to extract a string value 'questionText' from inside 'Pages' array. I used jsonPath() method with navigation path as given below which solved the problem.
JsonPath jsonPathEvaluator = response.jsonPath();
List<List<List<String>>> questions = jsonPathEvaluator.getList("pageGroups.pageGroups.pages.questions.questionText");
It gave me 3 ArrayLists one embedded in another corresponding to 3 arrays of 'pages'

how to update existing JSON file in java

This is my sample Json
{
"State": {
"version": "1",
"SName": "Test",
"shippingDetails": {
"Address1": "AP",
"ZipCode": "1236"
},
"Directions": {
"routes": [
{
"taxAmount": "0.0",
"Quantity": "5",
"bounds": {
"SerialVersion": [
{
"text": "1.7 km",
"value": "1729",
"time": "02633"
},
{
"text": "1.9 km",
"value": "1829",
"time": "02353"
},
{
"text": "17 km",
"value": "1059",
"time": "02133"
}
]
}
}
]
}
}
}
I want to update SName, ZipCode,taxAmount,Quantity, and text[1] values
are there any way to do this. I am taking JSON in a file and update tags are taking into HashMap
JSONObject jsonObject = new JSONObject("Your_JSON_String");
JSONObject jsonObjectForState = jsonObject.getJSONObject(“State”);
jsonObjectForState.put("Sname", "New_Value_Here");
put(...) will replace the current value with new value. Similarly, you can update the other values. Once you are done, you can convert it back using:
jsonObject.toString();
And write it back to the file.

Data of type org.json.JSONObject cannot be converted to JSONArray

I can't understand, why I have this error:
04-24 22:11:51.263: W/System.err(27504): org.json.JSONException: Value
<!--HERE JSON VALUE--> at data of type org.json.JSONObject cannot be
converted to JSONArray
This is my code:
JSONObject getProgile = null;
try {
//get json
getProgile = new JSONObject(CustomHttpClient.executeHttpGet(profileGetURL).toString());
//convert array
JSONArray array = getProgile.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject c = array.getJSONObject(i);
//get TAG_CUSTOMER
JSONObject customer = c.getJSONObject("Customer");
pName = customer.getString("name");
pLname = customer.getString("name");
}
UPD:
My json
{
"status": "success",
"data": {
"Customer": {
"id": "33",
"company_id": "1",
"name": "SDfsdf",
"birthdate": "14.02.1989",
"email": "dsfsdf#sf.ff",
"photo": "/files/clients_photos/33/(null)",
"bonuses": "50",
"created": "2015-02-14 12:22:46",
"modified": "2015-02-14 12:22:46",
"ref_id": null,
"ref_code": "6363696029",
"banned": null,
"ban_reason": null,
"ban_ending": null
},
"CustomerVisit": [],
"CustomerBonus": [
{
"id": "29",
"customer_id": "33",
"user_id": "4",
"product_id": null,
"operation": "plus",
"amount": "50",
"subject": "Загрузка фото при регистрации.",
"remain": null,
"modified": "2015-02-14 12:22:46",
"date": "14.02.2015",
"created": "14.02.2015 12:22"
}
],
"CustomerCar": [
{
"id": "41",
"customer_id": "33",
"car_brand_id": "9",
"car_model_id": "11530",
"year": "2020",
"vin": "sdfsdfsdf",
"photo": "",
"number": "dsfsdf",
"created": "2015-02-14 12:22:46",
"modified": "2015-02-14 12:22:46",
"car_brand_name": "BMW",
"car_model_name": "323"
}
],
"CustomerPhone": [
{
"id": "41",
"customer_id": "33",
"phone": "+380990010222",
"created": "2015-02-14 12:22:46",
"modified": "2015-02-14 12:22:46"
}
],
"Insurance": [],
"Event": [],
"Review": [],
"Reservation": []
}
}
JSON shows data is JSONObject rather than JSONArray, so call getProfile.getJSONObject ("data")
The problem is that you are trying to convert and JSON Object with JSON array therefore an error will occur.
If you just want to get the name then you can do this:
getProgile = new JSONObject(CustomHttpClient.executeHttpGet(profileGetURL).toString());
JSONObject obj1 = getProgile.getJSONObject("data");
JSONObject obj2 = array.getJSONObject("Customer");
String name = obj2.getString("name");

Convert string array into JSON object?

I got json[] from UI. I have to convert it into Json object how can I convert it with gson. An object which is received is like that:
[{"name":"name","value":"value"},{"name":"first","value":"100"},{"name":"hor","value":"95"},{"name":"conf","value":"95"}],[{"name":"vaRType","value":"INCRE"},{"name":"per","value":"100"},{"name":"hor","value":"95"},{"name":"conf","value":"95"}]
I used JsonObject obj = new JsoParser().parse(jsonStrnig).getAsJsonObject();
but it throws an exception.
Because it is not valid json object.
Your JSON should be the following as currently it's invalid...
[
[
{
"name": "name",
"value": "value"
},
{
"name": "first",
"value": "100"
},
{
"name": "hor",
"value": "95"
},
{
"name": "conf",
"value": "95"
}
],
[
{
"name": "vaRType",
"value": "INCRE"
},
{
"name": "per",
"value": "100"
},
{
"name": "hor",
"value": "95"
},
{
"name": "conf",
"value": "95"
}
]
]

Categories

Resources