Iterate through a collection of JSON Objects - java

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

Related

Read from .json file [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
Hii i am having trouble to read .json file in Java containing following structure,
{"id":"1", "name":"A", "address":{"plot no":"22", "street":"road"}}
{"id":"2", "name":"A", "address":{"plot no":"22", "street":"road"}}
{"id":"3", "name":"A", "address":{"plot no":"22", "street":"road"}}
{"id":"4", "name":"A", "address":{"plot no":"22", "street":"road"}}
I have such 10k records. I cant change structure. I want to read it and do processing on "address". I need an efficient way to read it and fetch only address. Any suggestions?
yourJsonObject is your json file extracted in java as a json object. And this:
JSONObject jso = yourJsonObject.getJSONObject("address") ;
will extract your "address" part as a json object. Then you can do all the classical processing on it.
You can use JSON simple library,i hope you take idea with this example ;
JSONParser parser = new JSONParser();
JSONArray a = (JSONArray) parser.parse(new FileReader("file name"));
for (Object o : a){
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
JSONArray cars = (JSONArray) jsonObject.get("cars");
for (Object c : cars)
{
System.out.println(c+"");
}
}

Gson to get Json value for a pie chart using Highcharts

I am working on Pie Charts using HighCharts.
The structure of JSON i needed is
data: [
['Firefox', 45.0],
['IE', 26.8],
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
I am using GSON to convert this into JSON object.
I tried to add a class 'Browser' which contains
private List browserName = new ArrayList();
private List browserValue = new ArrayList();
// passing the browser class object to Gson
gson.toJson(browser);
In graph I passed the data as
data: [
json.browserName,json.browserValue
]
But this didnt worked. How can I achieve the required JSON format when name and value is a list.
I added some quotes and braces to make your json valid. Then, it's a matter of looping through your data key which gives you an array of arrays.
String jsonString =
"{'data':[['Firefox',45.0],['IE',26.8],['Safari',8.5],['Opera',6.2],['Others',0.7]]}";
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject();
JsonArray data = jsonObject.get("data").getAsJsonArray();
for(int i = 0; i < data.size(); i++) {
JsonArray dataIndex = data.get(i).getAsJsonArray();
System.out.println(dataIndex.get(0));
System.out.println(dataIndex.get(1));
}
I find it helps me to visualize the json before writing code to go in and get values.

parse json using java (simplejson)

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.

Android: Exception when converting a String into a JSONObject

I get the following Error when I try to convert a JSON String into a JSONObject.
Value 48.466667|9.883333 at location of type java.lang.String
cannot be converted to JSONObject
The String is valid JSON, I tested it with http://jsonlint.com/
Example:
{"name":"An der Decke","location":"48.412583|10.0385","type":"Virtual","size":null,"status":"Available","difficulty":1,"rating":null,"terrain":1}
The code that produces the exception looks like that:
jsonObject = new JSONObject(result);
jsonArray = new JSONArray();
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONObject value = (JSONObject) jsonObject.get(key); <---- Exception
jsonArray.put(value);
} catch (JSONException e) {
// Something went wrong!
}
}
Is the pipe | symbol not a valid character in Java JSON?
EDIT:
The thing is, it works fine if the JSON String doesn't include the "location":"48.412583|10.0385" part...
You seem to misunderstand how the org.json library works.
As explained on the JSON homepage, a JSON value can be a string, number, object, array, true/false or null. The library maps these value types to String, Number subclasses, JSONArray, JSONObject, Boolean or null.
Not everything in that library is a JSONObject. In fact, a JSONObject is specifically used to represent a name/value pair object. JSONObject.get() can potentially return any of the aforementioned value types, that's why it needs to fall back to the greatest common denominator type: Object (and not JSONObject). Thus, casting everything to a JSONObject won't work.
It's your responsibility to ensure that you're casting to the correct type using your knowledge of the incoming data structure. This seems to be a problem in your case: your JSON string contains strings (for name, location, type and status), integers (for difficulty and terrain) and nulls (for size). What exactly are you trying to do with these?
If your goal is just to get a JSONArray of all your JSON string values, there's a much simpler way to do it.
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.toJSONArray(jsonObject.names());
System.out.println(jsonArray); // prints:
// [1,"Available","48.412583|10.0385","An der Decke",1,null,"Virtual",null]
With that aside, you were wrong to assume that every value encapsulated within JSON would be a JSON object itself. In fact, in your case none of them are. The correct types of all the values in your JSON are
// String
System.out.println(jsonObject.getString("name")); // An der Decke
System.out.println(jsonObject.getString("location")); // 48.412583|10.0385
System.out.println(jsonObject.getString("type")); // Virtual
System.out.println(jsonObject.getString("status")); // Available
// Null
System.out.println(jsonObject.isNull("size")); // true
System.out.println(jsonObject.isNull("rating")); // true
// Integer
System.out.println(jsonObject.getInt("terrain")); // 1
System.out.println(jsonObject.getInt("difficulty")); // 1
On the other hand, if your name was an embedded JSON object consisting of first, middle and last names, your JSON string (ignoring the rest of the keys for brevity) would have looked like
{"name": {"fname" : "An", "mname" : "der", "lname" : "Decke"}}
Now, we can put getJSONObject() to use because we really do have an embedded JSON object.
JSONObject jsonObj = new JSONObject("{\"name\":
{\"fname\" : \"An\", \"mname\" : \"der\", \"lname\" : \"Decke\"}}");
// get embedded "name" JSONObject
JSONObject name = jsonObj.getJSONObject("name");
System.out.println(name.getString("fname") + " "
+ name.getString("mname") + " "
+ name.getString("lname")); // An der Decke
The get() method of JSONObject returns a result of type Object. In this case, it seems it is a String. It's as if you were doing
JSONObject value = (JSONObject) new String("asdasdsa");
which obviously makes no sense as they are incompatible types.
Instead, retrieve the value, create a JSONObject from it and add it to the JSONArray.

java nested JSONArray

I want to know if it is possible to check if some key exists in some jsonArray using java. For example: lets say that I have this json string:
{'abc':'hello','xyz':[{'name':'Moses'}]}
let's assume that this array is stored in jsnArray from Type JSONArray.
I want to check if 'abc' key exists in the jsnArray, if it exists I should get true else I should get false (in the case of 'abc' I should get true).
Thnkas
What you posted is a JSONObject, inside which there is a JSONArray. The only array you have in this example is the array 'xyz', that contains only one element.
A JSONArray example is the following one:
{
'jArray':
[
{'hello':'world'},
{'name':'Moses'},
...
{'thisIs':'theLast'}
]
}
You can test if a JSONArray called jArray, included inside a given JSONObject (a situation similar to the example above) contains the key 'hello' with the following function:
boolean containsKey(JSONObject myJsonObject, String key) {
boolean containsHelloKey = false;
try {
JSONArray arr = myJsonObject.getJSONArray("jArray");
for(int i=0; i<arr.length(); ++i) {
if(arr.getJSONObject(i).get(key) != null) {
containsHelloKey = true;
break;
}
}
} catch (JSONException e) {}
return containsHelloKey;
}
And calling that in this way:
containsKey(myJsonObject, "hello");
Using regular expressions will not work because of the opening and closing brackets.
You could use a JSON library (like google-gson) to transform your JSON Array into a java array and then handle it.
JSON arrays don't have key value pairs, JSON objects do.
If you store it as a json object you can check the keys using this method:
http://www.json.org/javadoc/org/json/JSONObject.html#has(java.lang.String)
If you use JSON Smart Library in Java to parse JSon String -
You can parse JSon Array with following code snippet -
like -
JSONObject resultsJSONObject = (JSONObject) JSONValue.parse(<<Fetched JSon String>>);
JSONArray dataJSon = (JSONArray) resultsJSONObject.get("data");
JSONObject[] updates = dataJSon.toArray(new JSONObject[dataJSon.size()]);
for (JSONObject update : updates) {
String message_id = (String) update.get("message_id");
Integer author_id = (Integer) update.get("author_id");
Integer createdTime = (Integer) update.get("created_time");
//Do your own processing...
//Here you can check null value or not..
}
You can have more information in - https://code.google.com/p/json-smart/
Hope this help you...

Categories

Resources