how to retrieve JSON object from the JSON array - java

I am having the below JSON. Inside this JSON I am having "ticketDetails" as JSON array. From this array I want to retrieve the value of ticketPrice inside the json object "amount". How can I do that?
{
"ticketDetails": [{
"seq": 1,
"qty": 2,
"amount": {
"ticketPrice": 120,
"bookingFee": 50
},
"session": {
"id": 1001,
"date": "2013, 9, 15",
"time": "1300"
},
"venue": {
"id": "MTRG",
"name": "Adlabs Manipur",
"companyCode": "ADLB"
},
"event": {
"id": "ET00000001123",
"name": "Chennai Express",
"producerCode": "YRF"
},
"category": {
"ttypeCode": "00012",
"areaCatCode": "2414",
"type": "Gold",
"price": 270
}
}]
}
Any suggestion will helpful...

Below is the sample code for retrieving the ticketPrice from the given JSONObject:
JSONObject objData = (JSONObject)JSONSerializer.toJSON(data);
JSONArray objTicketDetailsJsonArr = objData.getJSONArray("ticketDetails");
for(int nSize=0; nSize < objTicketDetailsJsonArr.size(); nSize++){
String ticketPrice = "";
ticketPrice = objTicketDetailsJsonArr.getString("ticketPrice");
}
Below are the imports for the above code:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
source of JAR: http://json-lib.sourceforge.net/

you store your data within a variable
data = {...}
then you access it this way:
data.ticketDetails[0].amount.ticketPrice
if the ticketDetails have more than one element
you can loop over the ticketDetails array and store all the ticketPrice values within an other array, ticketPriceArray
the following would work fine in JavaScript:
var ticketPriceArray = data.ticketDetails.map(function(k){
return k.amount.ticketPrice;
});
if you are using another programming language a general loop would work fine also
for ( i; i< ticketDetails.length ; i++){
ticketPriceArray[i] = data.ticketDetails.amount.ticketPrice[i];
}
For Java check this tutorial:
http://answers.oreilly.com/topic/257-how-to-parse-json-in-java/

you can try this code:
JsonObject transactiondata = (JsonObject)Offer.get("transData");
JsonObject ticketdata = (JsonObject)transactiondata.get("tickets");
JsonObject offerData = (JsonObject)Offer.get("offerData");
JsonObject offerData1 = (JsonObject)offerData.get("offerconfig");
JsonArray jsonarr= (JsonArray)ticketdata.get("ticketDetails");
double ticketPrice = Double.parseDouble(jsonarr.get(0).getAsJsonObject().get("amount").getAsJsonObject().get("ticketPrice").getAsString());
System.out.println("ticketPrice:"+ticketPrice);

Related

Parsing JSONObject to access ID when there are multiple ID values (Java)

I am obtaining a JSON response from an API that gives me a list of call records formatted as JSON. I want to parse through the data and find the record ID, my trouble is that each JSON record has multiple ID's and I am not sure how to access the correct one. Keep in mind, I do not know the value of the ID is "3461487000073355176" prior to running the request.
This is my code to receive the JSON, I created a JSONObject so I can hopefully store the value.
1.
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(responseBody);
String prettyJsonString = gson.toJson(je);
JSONObject json = new JSONObject(prettyJsonString);
System.out.println("Json = " + json);
The JSON the ID I need to access has a comment next to it:
"data": [
{
"Owner": {
"name": "My namen",
"id": "346148700000017",
"email": "m#gmail.com"
},
"$state": "save",
"$process_flow": false,
"Street": "95## ### ######",
"id": "**3461487000073355176**", ----This is the ID I need -----
"Coverage_A_Dwelling": 100000,
"$approval": {
"delegate": false,
"approve": false,
"reject": false,
"resubmit": false
},
"Created_Time": "2020-12-10T09:05:17-05:00",
"Property_Details": "Primary Residence",
"Created_By": {
"name": "My name",
"id": "346148700000017",
"email": "m#gmail.com"
},
"Description": "Created on Jangl: https://jan.gl/crwp773ytg8",
"$review_process": {
"approve": false,
"reject": false,
"resubmit": false
},
"Property_State": "FL",
"Property_Street": "95",
"Roof_Material": "Asphalt Shingle",
"Full_Name": "Clare Em",
"Property_City": "Land ",
"Email_Opt_Out": false,
"Lead_I_D": "4FFEC0C5-FBA1-2463-DB9B-C38",
"Insured_1_DOB": "1942-02-20",
"$orchestration": false,
"Tag": [],
"Email": "cr#yahoo.com",
"$currency_symbol": "$",
"$converted": false,
"Zip_Code": "338",
"$approved": true,
"$editable": true,
"City": "Land O Lakes",
"State": "FL",
"Structure_Type": "Single Family",
"Prior_Carrier": {
"name": "Default Carrier (DO NOT DELETE OR CHANGE)",
"id": "3461487000000235093"
},
"Source": {
"name": "EverQ",
"id": "346148700006474"
},
"First_Name": "Clarence",
"Modified_By": {
"name": "My name",
"id": "3461487000000172021",
"email": "m#gmail.com"
},
"Phone": "7036159075",
"Modified_Time": "2020-12-10T09:05:17-05:00",
"$converted_detail": {},
"Last_Name": "####",
"$in_merge": false,
"$approval_state": "approved",
"Property_Zip": "34638"
}
],
"info": {
"per_page": 200,
"count": 1,
"page": 1,
"more_records": false
}
}
If I understood it correctly, you can get the id like this:
Here, json has the following value.
[
{
"Owner": {
"name": "My namen",
"id": "346148700000017",
"email": "m#gmail.com"
},
"id": "**3461487000073355176**"
...
}
]
Now I can iterate over JSONArray to get the id.
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
String id = (String) jsonObject.get("id");
System.out.println(id);
}
It prints out **3461487000073355176**.
You can do jsonObject.getJSONArray("data"); in your example to obtain JSON array.
The posted JSON response is missing the initial "{".
Your JSON contains data, which is a JSONArray of Owner objects. To get the id field of the first owner (array element 0):
// existing code
JSONObject json = new JSONObject(prettyJsonString);
System.out.println("Json = " + json);
// get the id field
JSONArray dataArray = (JSONArray)json.get("data");
JSONObject data0 = (JSONObject) dataArray.get(0);
JSONObject owner = (JSONObject) data0.get("Owner");
String id = owner.getString("id");
System.out.println(id);
Not sure if understood correctly but if you need to get all the IDs in that "level" why don't you try to model it as a class instead of using parser and let Gson do the parsing (this class might be useful later if you need to add more details)?
For example, defining something like this:
#Getter #Setter
// This models the response string from body
public class Response {
#Getter #Setter
// This models objects in the data list/array
public static class IdHolder {
// Only id because not interested of the rest
private String id;
}
// Only list of id holders because not interested of the rest
private List<IdHolder> data;
}
Then it would be as easy as:
Response res = gson.fromJson(responseBody, Response.class);
// Print out what you got
res.getData().stream().map(IdHolder::getId).forEach(System.out::println);

Want to read JSONArray with JSONObject, but got the error A non-empty JSON Pointer

My Json FILE (it´s an array! )
[
{
"datasetid": "country-flags",
"recordid": "d661d0a8676bf4d7563114c1d9c465987df22132",
"fields": {
"num_un": 32,
"geolocation": [
-38.416097,
-63.616672
],
"dialing_code": "54",
"a3_un": "ARG",
"country": "Argentina",
"flag": {
"mimetype": "image/png",
"format": "PNG",
"filename": "ar.png",
"width": 16,
"id": "fceb4235ce95c8597bfa77d0db0181a0",
"height": 11,
"thumbnail": true
},
"a2_iso": "AR"
},
"geometry": {
"type": "Point",
"coordinates": [
-63.616672,
-38.416097
]
},
"record_timestamp": "2016-09-26T07:48:38.162+02:00"
},
more...
]
So i want to get the value from coordinates. So for this i tried to work with this:
JsonReader jsonReader = Json
.createReader(new FileReader(getClass().getResource("country-flags.json").getPath()));
JsonArray arr = jsonReader.readArray();
for(int i = 1; i<arr.size();i++)
{
JsonObject obj = arr.getJsonObject(i);
System.out.println("coordinates: " + obj.containsKey("\"coordinates\""));
System.out.println("##########");
System.out.println(obj.getValue("\"coordinates\""));
}
But i got the error:
javax.json.JsonException: A non-empty JSON Pointer must begin with a
'/'
Can someone help me out ?!
Your code obj.containsKey("\"coordinates\"") will return false as coordinates is NOT a top level key, but is a 2nd level (nested) key. If you print obj.keySet(), you will get [datasetid, recordid, fields, geometry, record_timestamp] (first / top level keys only).
If the structure of your JSON is fixed, you can use the following code:
for(int i = 1; i<arr.size();i++)
{
JsonObject obj = arr.getJsonObject(i);
JsonObject jsonChildObject = obj.getJsonObject("geometry");
if(jsonChildObject.containsKey("coordinates"))
System.out.println(jsonChildObject.getValue("/coordinates"));
}
Notice the / in front of the getValue method's coordinates param. I think that was the reason you were here in the first place.

how to get elements from JSONObject and write it to file

i have a following JSONObject
{"elements": [
{
"name": "StartLabelFormat",
"value": "^XA"
},
{
"name": "shipperAddressLine1",
"value": "Street1",
"format": {"Text": {
"orientation": "N",
"height": "28",
"width": 20,
"fontname": 0,
"y": 373,
"x": 20
}}
},
{
"name": "EndLabelFormat",
"value": "^XZ"
}
]}
Now i want to get element from this Object and write it to a file.
For Example, for this block
{
"name": "shipperAddressLine1",
"value": "Street1",
"format": {"Text": {
"orientation": "N",
"height": "28",
"width": 21,
"fontname": 0,
"y": 373,
"x": 20
}}
},
I want to write in file as
^FT 20, 373 ^A0N, 28, 21 ^FDStreet1^FS.
Please help me to do this.
How to do it ?
If you meet {} in your code , you can use JSONObject to parse it .
If you meet [] in your code , you can use JSONArray to parse it .
And if you meet [] in your code , you can use for loop to get value in it .
And you should use try catch in your code .
Try this in your code .
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray elements = jsonObject.getJSONArray("elements");
for (int i = 0; i < elements.length(); i++) {
JSONObject jsonObject1 = elements.getJSONObject(i);
String name = jsonObject1.optString("name");
String value = jsonObject1.optString("value");
JSONObject format = jsonObject1.optJSONObject("format");
JSONObject Text = format.optJSONObject("Text");
String orientation = Text.optString("orientation");
String height = Text.optString("height");
String width = Text.optString("width");
}
} catch (JSONException e) {
e.printStackTrace();
}
Note
And use optString and optJSONObject in your code . If format is null ,it will not return error .
And you can judge that JSONArray's length is not 0 and not null in the code .
To get this element from JsonArray
JsonObject yourElement = yourJsonArray.get(index);
Simply, you can use gson library for parsing json to objects.
public class Staff {
private String name;
private String value;
//...
and use Gson
String jsonInString = " {
"name": "shipperAddressLine1",
"value": "Street1"
}";
Staff staff = gson.fromJson(yourElement.toString() , Staff.class);
After that you can write in file by using your custom toString() method inside Staff class.
P.S. to convert JsonObject to String you can use also toString() method.

JSON: Get list of JSON Objects

In java how can I pull out the JSON objects enclosed in the "{}"?
I have tried:
JSONObject obj = new JSONObject(jstring);
obj.getJSONArray("fileName");
But it only return the first object. How do I get a list with both objects?
JSON:
[
{
"fileName": [
"file1"
],
"date": [
"8/25/2015 0:00"
],
"time": [
"7/16/2009 16:51"
],
"id": "1",
"version_": 1
},
{
"fileName": [
"file1"
],
"date": [
"8/25/2015 0:00"
],
"time": [
"7/16/2009 16:51"
],
"id": "1",
"version_": 1
}
]
Your root JSON is an Array, so first create a JSONArray from your String.
Do this:
JSONArray arr = new JSONArray(jstring);
for (int i = 0; i < arr.length(); i++) { // Walk through the Array.
JSONObject obj = arr.getJSONObject(i);
JSONArray arr2 = obj.getJSONArray("fileName");
// Do whatever.
}
For more info, please refer to the docs on JSONArray and JSONObject.
You have to directly construct JSONArray from JSON string in this case.
JSONArray arr = new JSONArray(jstring);
JSONArray jsonArray = new JSONArray(jstring);

Problems parsing JSON in Java

I have this json:
[{
"name": "prog 1",
"show": [{
"name": "n1",
"time": "01.10 "
}, {
"name": "n2",
"time": "01.35 "
}]
}, {
"name": "prog 2",
"show": [{
"name": "n1",
"time": "01.10 "
}, {
"name": "n2",
"time": "01.35 "
}]
}]
Now trying to parse it in Java like:
JSONObject json=new JSONObject(json_str);
throws an Exception, since it doesn't begin with {, but [ since it's an array. I can parse this without problem in js, but aparently I cannot load an JSONArray with this string...
use: JSONArray objArray = new JSONArray (json_str);
// to access the individual objects inside the array:
for(int i=0;i<objArray.length();i++)
{
JSONObject obj = objArray.getJSONObject(i);
}
Have you tried this:
JSONArray arr = new JSONArray(stringWithContent);
Then access it like :
for(int i = 0; i<arr.length();i++){
System.out.println(arr.get(i));
}
You can try following code
JSONObject jObject = new JSONObject(json_str);
JSONArray array = jObject.getJSONArray("show");
for(int i = 0 ; i < array.length() ; i++)
{
System.out.println(array.getJSONObject(i).getString("name"));
System.out.println(array.getJSONObject(i).getString("time"));
}
It will helpful ...

Categories