parse json using java (simplejson) - java

I need to parse json which I get from YQL but I am having trouble as I am not getting the results I need. I am using simple json (https://code.google.com/p/json-simple/wiki/DecodingExamples) and trying to follow the documentation. The problem is the example they show are very limited (I am very new to json). I want to extract everything in the array (Sy, Date, O, H, L, C, and V ). In the documentation they show how to extarct elements from an array if the json object is just as an array, but I have an array + some extra stuff on top:
{"query"
{"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
This is the full json object, how would I extract just the array?
{"query"
{"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
{"array":[{"Sy":"Y","Date":"2010-03-10","O":"16.51","H":"16.94","L":"16.51","C":"16.79","V":"33088600"},
{"Sy":"Y","Date":"2010-03-09","O":"16.41","H":"16.72","L":"16.40","C":"16.53","V":"20755200"},
{"Sy":"Y","Date":"2010-03-08","O":"16.32","H":"16.61","L":"16.30","C":"16.52","V":"30554000"}
]}}}

i use https://code.google.com/p/org-json-java/downloads/list
this is simple
try{
String json = "JSON source";
JSONObject j = new JSONObject(json);
JSONArray arr = j.getJSONObject("query").getJSONObject("results").getJSONArray("array");
for(int i=0; i<arr.length(); i++){
JSONObject obj = arr.getJSONObject(i);
String sy = obj.getString("Sy");
String date = obj.getString("Date");
String o = obj.getString("O");
String h = obj.getString("H");
String l = obj.getString("L");
String c = obj.getString("C");
String v = obj.getString("V");
}
}
catch(JSONException e){
}

You have to extract the array you need piece by piece.
JSONParser parser=new JSONParser();
String s="{YOUR_JSON_STRING}";
JSONArray array=parser.parse(s).get("query") //"query"
.get("result") // "query->result"
.get("array"); // THE array you need
Note that you might need to use try...catch... block to deal with exceptions.
Since you are using java, I highly recommend gson, which is written by google. It can convert json to object directly, which means you don't need to get the array deep inside the json step by step. https://code.google.com/p/google-gson/
Generally speaking, you can use gson to parse json piece by piece with jsonparser or, convert the whole json to a object with gson.

Related

Iterate through a collection of JSON Objects

I have a JSON file called mani.json which contains several objects, each object containing 3 key-value pairs that have information about some artifact files.
{ "art_src_path": "source/subdir/hi-there.txt","art_id": "6945-L9.txt","art_date": "2018:03:10 01:10:33"}
{ "art_src_path": "source/hello-world.txt","art_id": "10426-L13.txt","art_date": "2018:03:10 01:10:33"}
{ "art_src_path": "source/subdir/testfile.txt","art_id": "50518-L66.txt","art_date": "2018:03:10 01:10:33"}
I want to iterate through each of these objects in another file called FileTest.java and get the value corresponding to art_src_path. My FileTest.java file contains code that looks like this:
<!-- language: java -->
JSONParser parser = new JSONParser();
JSONObject a = (JSONObject) parser.parse(new FileReader("mani.json"));
for (Object o : a ) {
String path = (String) o.get("art_src_path");
File myFile = new File(path);
System.out.println("Source path: "+path);
}
NetBeans prompts an error and states that the object returned by the parser is not iterable and so I cannot use the for-each loop.
While this code, with certain modifications, worked well for iterating through an array of objects, it seems to fail for iterating through an object of objects.
So I have 2 questions:
What does the parser return; so that it is iterable for an array but not for an object?
How can I iterate through all the objects in mani.json to get the value for art_src_path from each object?
Almost all the answer so far tell me how to iterate over an array of objects. I am able to do that. I need to know how to iterate over an object of objects.
Thank you.
Is mani.json file is correctly json format? If so, the list would be JSONArray. JSONArray can iterate but JSONObject cannot.
If mani.json file is not json format but just text file. read line by line and parse each as JSONObject.
String strJson = "[{ \"art_src_path\": \"source/subdir/hi-there.txt\",\"art_id\": \"6945-L9.txt\",\"art_date\": \"2018:03:10 01:10:33\"},"+
"{ \"art_src_path\": \"source/hello-world.txt\",\"art_id\": \"10426-L13.txt\",\"art_date\": \"2018:03:10 01:10:33\"},"+
"{ \"art_src_path\": \"source/subdir/testfile.txt\",\"art_id\": \"50518-L66.txt\",\"art_date\": \"2018:03:10 01:10:33\"}]" ;
System.out.println("input = "+strJson) ;
JSONParser parser = new JSONParser() ;
JSONArray a = (JSONArray) parser.parse(strJson) ;
for (Object o:a) {
String path = (String) ((JSONObject) o).get("art_src_path") ;
System.out.println("source path:"+path) ;
}

Json reponse with repeated json objects without parent json arry

Above is the json response I am receiving from a url. There are repeated json objects in the response at the same level without a parent json array, I believe that these objects should be within a josn array so one can loop through the objects to access their information.
Is it really an error of missing json array? if not then how can be looped through and receive information in such scenario. Thanks for your time and help.
How can be looped through and receive information in such scenario ?
You should use ITERATOR for this case .
FYI
Iterator is a way to traverse the data over the collection objects.
JSONObject jOBJECT = new JSONObject(success);
Iterator iteratorObj = jOBJECT.keys();
while (iteratorObj.hasNext())
{
String getJsonObj = (String)iteratorObj.next();
System.out.println("Key: " + Key + "------>" + getJsonObj); // 78,40,121,132
}
Here is the detailed solution for such pattern of objects in the service response.
https://stackoverflow.com/a/12870643/1925394
this code maybe can help you:
try {
String data="";//this is you json
JSONObject jsonObject=new JSONObject(data);
JSONArray messages = jsonObject.getJSONArray("message");//get a array
//loop the arrat to output
for (int i = 0; i < messages.length(); i++) {
JSONObject msg=messages.getJSONObject(i);
String id= msg.getString("id");
String username= msg.getString("username");
System.out.println("id:"+id+",username:"+username);
}
} catch (JSONException e) {
e.printStackTrace();
}
but,I advise you don't use this in your project, you can consider Gson ,use this you can transfer json to java model,and then it's easy to use.

JSON Exception String cannot be converted to JSON Object

I am trying to parse json and running into a small problem.
my json string looks like this:
String json =
[
"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}",
"{caption=adsf, url=/storage/emulated/0/DCIM/Camera/20140330_103412.jpg}"
]
and my code so far looks like this:
try {
JSONArray jsonObj = new JSONArray(json);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String img = c.getString("url");
String cap = c.getString("caption");
But its throwing an exception type java.lang.String cannot be converted to JSONObject
What am I doing wrong?
EDIT
If its helpful to anyone, I ended up using GSON to get my json in the correct expected format like this:
Gson gson = new Gson();
String json = gson.toJson(mylist);
Your JSON array contains elements like
"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}"
which is a String not a JSON object. You can't therefore try to retrieve it as a JSONObject.
Seems like you're getting JSON that isn't in the format you expected. Even if you got rid of the "" around it, it still wouldn't be valid JSON, so I don't understand its purpose enough to help you.

What Format is this List in? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 8 years ago.
I'm receiving data in the format:
"result": {"FirstData": {"One": 1, "Two": 2,...
First of all, what is this called usually in Java (2D array)?
Secondly, how do I loop over this to extract the strings?
I understand that if I only had "FirstData" in my array I can do:
public void onSuccess( String[] result)
{
for( String Name : result ) {
System.out.println(Name);
}
Going through the same logic for 2D arrays, it doesn't seem to print things out:
public void onSuccess( JSONObject result)
{ //Parse here
}
EDIT:
Yes it's JSON and it looks like the code has gson (google JSON) installed
EDIT 2:
ABOVE CODE NOW CORRECTED
JSON. Use a JSON parser to read the data. One popular parser for Java : google-gson
It looks kind of like JSON. JSON-strings is built like this:
Key: Values
However, Values can be new "key:values" so you can have:
"Key": ["InnerKey1":"Value1","Innerkey2","Value2"], "Key2": ["InnerKey1":"Value1","Innerkey2","Value2"] etc.
For you source:
JSONObject myJSONObject = new JSONObject("Your resultstring goes here");
JSONObject resultObject = myJSONObject.getJSONObject("result");
JSONObject FirstDataObject = resultObject.getJSONObject("FirstData"); //Object with JSONObjects "One","Two" etc
//Since the part " {"One": 1, "Two": 2,..." in your string isn't an JSONArray you cannot do the following but if it were like this "["One": 1, "Two": 2,..." your could do this:
JSONArray FirstDataArray = resultObject.getJSONObject("FirstData"); //Array with JSONObjects "One","Two" etc
JSONArray arr = resultObject.getJSONArray("FirstData");
for (int i = 0; i < arr.length(); i++)
{
String number = arr.getJSONObject(i).getString(0);
......
}
You can try using Google Gson, https://code.google.com/p/google-gson/. It can take JSON strings and convert them to Java objects.
Use a JSON parser for Java and you can probably convert it into objects. You can find a variety of Java-based JSON parsers on http://www.json.org/
This string is in the JSON format and hence it is recommended to use a JSON parser.
Read about JSON format in http://www.json.org/.
This link provides explains about JSON in java http://www.json.org/java/

How to access nested objects of a Json File

the string I have into "jsonString" is the content of this link: http://85.18.173.82/cineca/wp5/json/events.json
Now I want the value "Day" of the second "Event".
JSONObject o = new JSONObject(jsonString);
String day = o.getString("XXXXXXXXXX");
System.out.println(day);
What does I have to put as argument of o.getString?
Many thanks
JSONObject obj = new JSONObject(json);
JSONArray array = obj.getJSONArray("Events");
for(int i = 0 ; i < array.length() ; i++){
System.out.println(array.getJSONObject(i).getJSONObject("Event").getString("Day"));
}
In this way, you can access, thanks.
The way you're constructing your JSONObject is wrong. By using this constructor you're not reading the json from that URL, you're actually using that string as a json representation (which it is not).
If you want to first read the json from your URL you'll have to do an HTTP GET request and then construct a JSONObject out of the response.
For more info, take a look at JSONObject docs

Categories

Resources