json parsing using JSONObject - java

My data is like this:
{
"region":
["{'price':'119','volume':'20000','pe':'0','eps':'4.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'}",
"{'price':'112','volume':'20000','pe':'0','eps':'9.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'}",
"{'price':'118','volume':'20000','pe':'0','eps':'1.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'}"
]
}
I am doing like below;
JSONObject jsonObj = new JSONObject(jsonString);
JSONArray regionArray = jsonObj.getJSONArray("region");
How do I get each price..
for (int i = 0; i < regionArray.length(); i++) {
JSONObject item = regionArray.getJSONObject(i);
System.out.println(item.getString("price"));
}
Caused by: com.gemstone.org.json.JSONException: JSONArray[0] is not a JSONObject.

You have an array of Strings, not of JSON objects, so you can't do JSON object methods on it.
In order for your code to work, your JSON would have to look like this:
{
"region": [
{
"price": "119",
"volume": "20000",
"pe": "0",
"eps": "4.22",
"week53low": "92",
"week53high": "134.4",
"daylow": "117.2",
"dayhigh": "119.2",
"movingav50day": "115",
"marketcap": "0",
"time": "2015-11-25 05:13:34.996"
},
{
"price": "112",
"volume": "20000",
"pe": "0",
"eps": "9.22",
"week53low": "92",
"week53high": "134.4",
"daylow": "117.2",
"dayhigh": "119.2",
"movingav50day": "115",
"marketcap": "0",
"time": "2015-11-25 05:13:34.996"
},
{
"price": "118",
"volume": "20000",
"pe": "0",
"eps": "1.22",
"week53low": "92",
"week53high": "134.4",
"daylow": "117.2",
"dayhigh": "119.2",
"movingav50day": "115",
"marketcap": "0",
"time": "2015-11-25 05:13:34.996"
}
]
}
I just replaced that automatically in a text editor. You can actually let the numbers out of their "" enclosure if you want.
Have a look at it here: http://www.jsoneditoronline.org/
And here's some info on Json: http://www.json.org/

Related

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.

Write json strings using java (JSP)

I want to create a json string like below.
"data": [{
"id": "1",
"data": "one",
"color": "008ee4"
},{
"id": "2",
"data": "two",
"color": "008ee4"
}]
So far I have come up with this.
<%
JSONObject outerObject = new JSONObject();
JSONArray outerArray = new JSONArray();
JSONObject innerObject = new JSONObject();
JSONArray innerArray = new JSONArray();
innerObject.put("label", "1");
innerObject.put("value", "one");
innerObject.put("color", "008ee4");
outerObject.put("data", outerArray);
System.out.println(outerObject.toString());
%>
And it gives the output like
{"data":[]}
I want to remove those curly brackets and input data inside square brackets. Please help me.
UPDATE
{
type: "line",
renderAt: "chartContainer1",
width: "500",
height: "300",
dataFormat: "json",
"dataSource": {
"chart": {
"caption": "Total Revenues from 2008-2013",
"numberprefix": "$",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"plotbordercolor": "008ee4",
"plotborderthickness": "3",
"showvalues": "0",
"divlinecolor": "CCCCCC",
"showcanvasborder": "0",
"tooltipbgcolor": "00396d",
"tooltipcolor": "FFFFFF",
"tooltipbordercolor": "00396d",
"numdivlines": "2",
"yaxisvaluespadding": "20",
"anchorbgcolor": "008ee4",
"anchorborderthickness": "0",
"showshadow": "0",
"anchorradius": "4",
"chartrightmargin": "25",
"canvasborderalpha": "0",
"showborder": "0"
},
"data": [
{
"label": "2009",
"value": "4400000",
"color": "008ee4"
},
{
"label": "2010",
"value": "4800000",
"color": "008ee4"
},
{
"label": "2011",
"value": "5500000",
"color": "008ee4"
},
{
"label": "2012",
"value": "6700000",
"color": "008ee4",
"anchorradius": "7",
"tooltext": "Historical high"
},
{
"label": "2013",
"value": "4200000",
"color": "008ee4"
}
]
}
}
Above is the main json file. I just want to replace the data part with my data.
Do it like this:
JSONObject outerObject = new JSONObject();
JSONArray outerArray = new JSONArray();
JSONObject innerObject = new JSONObject();
JSONArray innerArray = new JSONArray();
innerObject = new JSONObject();
innerObject.put("label", "1");
innerObject.put("value", "one");
innerObject.put("color", "008ee4");
innerArray.add(innerObject);
outerObject.put("data", innerArray);
System.out.println(outerObject.toString());

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

How to add element to json data

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"
}

Categories

Resources