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 ...
Related
I'm using org.json.simple library and I have a json which looks like below
[
{
"lastName": "abc",
"firstName": "def",
"email": "abc#test.com",
},
{
"lastName": "xyz",
"firstName": "pqr",
"email": "xyz#test.com",
}
]
I need to add a header node. for example .. it should look like below. How to add "users" ??
{
"users" :
[
{
"lastName": "abc",
"firstName": "def",
"email": "abc#test.com",
},
{
"lastName": "xyz",
"firstName": "pqr",
"email": "xyz#test.com",
}
]
}
I already have org.json.simple.JSONObject for the above json..now I just need to add "users" at the top of json.
Put you existing array in to a new object.
JSONParser parser = new JSONParser();
JSONArray arr = (JSONArray) parser.parse("[{\"lastName\": \"abc\", \"firstName\": \"def\", \"email\": \"abc#test.com\" }, { \"lastName\": \"xyz\", \"firstName\": \"pqr\", \"email\": \"xyz#test.com\" }]");
System.out.println(arr); // First Json object (arr)
JSONObject obj = new JSONObject();
obj.put("users", arr);
System.out.println(obj); // Second Json object
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.
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);
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);
I parsing some data from a json file. Here is my JSON File.
[
{
"topic": "Example1",
"contact": [
{
"ref": [
1
],
"corresponding": true,
"name": "XYZ"
},
{
"ref": [
1
],
"name": "ZXY"
},
{
"ref": [
1
],
"name": "ABC"
},
{
"ref": [
1,
2
],
"name":"BCA"
}
] ,
"type": "Presentation"
},
{
"topic": "Example2",
"contact": [
{
"ref": [
1
],
"corresponding": true,
"name": "XYZ"
},
{
"ref": [
1
],
"name": "ZXY"
},
{
"ref": [
1
],
"name": "ABC"
},
{
"ref": [
1,
2
],
"name":"BCA"
}
] ,
"type": "Poster"
}
]
I can fetch and store data one by one. Like this one
JSONArray getContactsArray = new JSONArray(jsonObject.getString("contact"));
for(int a =0 ; a < getContactsArray.length(); a++)
{
JSONObject getJSonObj = (JSONObject)getContactsArray.get(a);
String Name = getJSonObj.getString("name");
}
1)Now, my question is there any way to get all name values for each array with single query.
2) Can I get all those values in an Array ?
Please correct me, if I am doing anything wrong. Thank you.
Iteration cannot be avoided here as org.json and other Json parsers as well provide random access to objects but not to their properties collectively (as a collection). So, you can't query something like "all name properties of all contact objects" unless you probably get a Json parser like Gson to unmarshall it that way.
But, that's too much to just avoid a for loop when you can definitely shorten the parse by making use of the appropriate API methods to avoid unnecessary object casts.
JSONArray contacts = jsonObject.getJSONArray("contact");
String[] contactNames = new String[contacts.length()];
for(int i = 0 ; i < contactNames.length; i++) {
contactNames[i] = contacts.getJSONObject(i).getString("name");
}
Better to use a json parser such as GSon or Jackson to marshall your json to a java object. Then you can write utitlity method in your java class to retrieve all the names in that object.
Try this:
Create JSONObject of your file and try to get array of all names and iterate it to get all values.
public static String[] getNames(JSONObject jo) {
int length = jo.length();
if (length == 0) {
return null;
}
Iterator i = jo.keys();
String[] names = new String[length];
int j = 0;
while (i.hasNext()) {
names[j] = (String) i.next();
j += 1;
}
return names;
}