I am a newbie to json parsing, I have grabbed a json string from a request and now I need to parse it with java. I'm using simple-lib for this. But I'm really stuck as I'm not familiar with it. I need to extract following data
I used following java code for that but it's not giving me the result I need, please someone help me...
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("test.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("content");
Iterator<String> iterator = msg.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
Sample JSON
{
"status": 200,
"message": "ok",
"timestamp": "2014-05-22T14:29:56.824+03:00",
"pagesCount": 1,
"version": "1.1",
"pages": [
{
"number": 100,
"subpages": [
{
"number": 1,
"timestamp": "2014-05-22T13:41:41.116+03:00",
"content": "text"
},
Something like this perhaps?
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader("test.json"));
JSONArray pages = (JSONArray) jsonObject.get("pages");
if (pages != null) {
for (Object p : pages) {
JSONObject page = (JSONObject) p;
JSONArray subPages = (JSONArray) page.get("subpages");
if (subPages != null) {
for (Object sp : subPages) {
JSONObject subPage = (JSONObject) sp;
System.err.println(subPage.get("content"));
}
}
}
}
You are requesting for the value that corresponds to the key content from your outermost object, but no such key exists in your sample input. In addition, the only field named content has a string as its value and not a JSON array.
To get at the content field you would need to walk the object hierarchy until you reach the element that you need, using something along these lines:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(new FileReader("test.json"));
JSONArray pages = (JSONArray) json.get("pages");
// Page 10
JSONObject page = (JSONObject) pages.get(10);
// Subpages of page 10
JSONArray subpages = (JSONArray) page.get("subpages");
// Subpage 7 of page 10
JSONObject subpage = (JSONObject) subpages.get(10);
// Content of subpage 7 of page 10
String content = (String) subpage.get("content");
Please note that I am assuming that e.g. index 10 corresponds to page 10. That may not be true in your case; pages may not be zero-indexed, there may be missing pages or they may not be in the correct order. In that case you will have to iterate over the page and subpage lists and test the value of the number field to find the object that you need.
In any case, if you are indeed using json-simple, as seems to be the case, then JSONObject is a subclass of HashMap and JSONArray a subclass of ArrayList. Therefore, their interfaces should be quite familiar to you.
Disclaimer: Untested code - exception and other error handling removed for brevity
First of all, The json is not valid (if you pasted it complete)
In JSON "{}" is an object, and "[]" is an array, others are just key value pairs.
Simply you can do like this without using parser ,
JSONObject objResponseJSON = new JSONObject(responseJSONString);
int status = (int) objResponseJSON.getInt("status");
//fetch other
JSONArray pages = objResponseJSON.getJSONArray("pages");
for(int count = 0; count < pages.length(); count++){
//fetch other
JSONObject objJSON = pages.getJSONObject(count);
JSONArray subpages = objJSON.getJSONArray("subpages");
for(int count1 = 0; count1 < subpages.length(); count1++){
JSONObject objSubpageJSON = subpages.getJSONObject(count1);
//fetch other
int number = (int) objSubpageJSON.getInt("number");
}
}
Related
I have created a .json file:
{
"numbers": [
{
"natural": "10",
"integer": "-1",
"real": "3.14159265",
"complex": {
"real": 10,
"imaginary": 2
},
"EOF": "yes"
}
]
}
and I want to parse it using Json Simple, in order to extract the content of the "natural" and the "imaginary".
This is what I have written so far:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); //the location of the file
JSONObject jsonObject = (JSONObject) obj;
String natural = (String) jsonObject.get("natural");
System.out.println(natural);
The problem is that the value of natural is "null" and not "10". Same thing happens when I write jsonObject.get("imaginary").
I have looked at many websites (including StackOverflow), I have followed the same way most people have written, but I am unable to fix this problem.
You need to find the JSONObject in the array first. You are trying to find the field natural of the top-level JSONObject, which only contains the field numbers so it is returning null because it can't find natural.
To fix this you must first get the numbers array.
Try this instead:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); //the location of the file
JSONObject jsonObject = (JSONObject) obj;
JSONArray numbers = (JSONArray) jsonObject.get("numbers");
for (Object number : numbers) {
JSONObject jsonNumber = (JSONObject) number;
String natural = (String) jsonNumber.get("natural");
System.out.println(natural);
}
The object in your file has exactly one property, named numbers.
There is no natural property.
You probably want to examine the objects inside that array.
Adding on to #Jermey Hanion's answer and comment, here is what I did to get "imaginary" and "natural"
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); //the location of the file
JSONObject jsonObject = (JSONObject) obj;
JSONArray numbers = (JSONArray) jsonObject.get("numbers");
for (Object number : numbers) {
JSONObject jsonNumber = (JSONObject) number;
String natural = (String) jsonNumber.get("natural");
JSONObject complex = (JSONObject) jsonNumber.get("complex");
String imaginary = (String) complex.get("imaginary");
System.out.println(natural);
}
Jeremey's answer for getting imaginary is not correct, or maybe it was correct. The above snippet is to my knowledge working on my project.
PS. Sorry for reviving the thread but I thought it would be a useful resource for people looking to learn JSON.simple
I'm parsing this document:
http://pastebin.com/M3Gsbf1t
as you can see it's kind of big. This document was generated by Youtube Data API v3.
I want to get all "title" elements and display them.
My code:
Object obj = parser.parse(str); // str contains the JSON code
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("title");
Iterator iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
but it returns "NullPointerException".
If I replace the "title" with the "items" it works fine but it returns me a lot of informations that I don't need.
I'm using the JSON.simple library.
Thanks for help :)
This code should work:
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("items");
Iterator iterator = msg.iterator();
while (iterator.hasNext()) {
//System.out.println(iterator.next());
JSONObject item = (JSONObject) iterator.next();
JSONObject item_snippet = (JSONObject) item.get("snippet");
System.out.println( item_snippet.get("title"));
}
You have a JSONObject at the root of your JSON string. In it, there's an JSONArray named items. From it you have to pull out individual items in while loop.
For each item there's JSONObject snippet nested in. Finally you'll find your title string in it.
jquery solution, this should give you an array of titles unless I am reading the object wrong.
titles = [];
obj = $.parseJSON(str);
$.each(obj.items,function(i,v{
titles.push(v.snippet.title);
});
Should be something like this:
Object obj = parser.parse(str); // str contains the JSON code
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("items");
Iterator iterator = msg.iterator();
while (iterator.hasNext()) {
// cast next item to JSONObject
JSONObject item = (JSONObject) iterator.next();
// grab the title
System.out.println(item.get("title"));
}
I am using the following library to parse an object:
{"name": "web", "services": []}
And the following code
import com.json.parsers.JSONParser;
JSONParser parser = new JSONParser();
Object obj = parser.parseJson(stringJson);
when the array services is empty, it displays the following error
#Key-Heirarchy::root/services[0]/ #Key:: Value is expected but found empty...#Position::29
if the array services has an element everything works fine
{"name": "web", "services": ["one"]}
How can I fix this?
Thanks
Try using org.json.simple.parser.JSONParser
Something like this:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(stringJson);
Now to access the fields, you can do this:
JSONObject name = jsonObject.get("name"); //gives you 'web'
And services is a JSONArray, so fetch it in JSONArray. Like this:
JSONArray services = jsonObject.get("services");
Now, you can iterate through this services JSONArray as well.
Iterator<JSONObject> iterator = services.iterator();
// iterate through json array
while (iterator.hasNext()) {
// do something. Fetch fields in services array.
}
Hope this would solve your problem.
Why do you need parser?
try this:-
String stringJson = "{\"name\": \"web\", \"services\": []}";
JSONObject obj = JSONObject.fromObject(stringJson);
System.out.println(obj);
System.out.println(obj.get("name"));
System.out.println(obj.get("services"));
JSONArray arr = obj.getJSONArray("services");
System.out.println(arr.size());
I solve the problen with https://github.com/ralfstx/minimal-json
Reading JSON
Read a JSON object or array from a Reader or a String:
JsonObject jsonObject = JsonObject.readFrom( jsonString );
JsonArray jsonArray = JsonArray.readFrom( jsonReader );
Access the contents of a JSON object:
String name = jsonObject.get( "name" ).asString();
int age = jsonObject.get( "age" ).asInt(); // asLong(), asFloat(), asDouble(), ...
Access the contents of a JSON array:
String name = jsonArray.get( 0 ).asString();
int age = jsonArray.get( 1 ).asInt(); // asLong(), asFloat(), asDouble(), ...
I have a JSON Object which converted into String and saved into database .But when i am trying to get it back it is throwing exception.My object is something like that...
{"COLUMN":["Type","Sub Type","F.P.","P.P.","Process","Due To Start"]}
How can we get the data back in Normal form?
My Java Code is.....
JSONObject obj = new JSONObject();
JSONArray the_json_array = obj.getJSONArray(userReorderOption);
int size = the_json_array.size();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
arrays.add(another_json_object);
}
And Exception i am getting....
net.sf.json.JSONException: JSONObject["{\"TASKLIST_COLUMN_REORDER\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}"] is not a JSONArray.
And this is java Code how i am creating JSON Object and saving into database...
String userReorderSelection;
Set set = new LinkedHashSet(userReorderSelection);
JSONObject json = new JSONObject();
json.accumulate("COLUMN", set);
saveJSONObj("PrimaryKeyColumn", json.toString());
Thanks Tichodroma,
But as i told i am using net.sf.json.JSONObject class and above things we can achieve from this class too..What i did to solve the above issue?...Please have a look on the Java code...
JSONObject jsonObj = new JSONObject();
JSONObject obj = jsonObj.fromObject(userReorderOption);
JSONArray columnName = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < columnName.size(); i++) {
System.out.println(columnName.getString(i));
}
This code work fine for me with my Json Jar**(net.sf.json)**
Your JSON is not a JSONArray.
A JSONArray is an ordered sequence of values.
You have a JSONObject.
A JSONObject is an unordered collection of name/value pairs.
Edit:
Using the JSON implementation from org.codehaus.jettison.json, you can do this:
String json = "{\"COLUMN\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}";
JSONObject obj = new JSONObject(json);
JSONArray column = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < column.length(); i++) {
final String field = column.getString(i);
System.out.println(field);
}
Result:
Type
Sub Type
F.P.
P.P.
Process
Due To Start
I am working in android. I want to parse my json data.
This is my json data:-
{
"response":{
"groups":[
{
"type":"nearby",
"name":"Nearby",
"items":[
{
"id":"4ed0c8f48231b9ef88fe5f09",
"name":"Banayan Tree School",
"contact":{
},
"location":{
"lat":26.857954980225713,
"lng":75.76602927296061,
"distance":510
},
"categories":[
{
"id":"4bf58dd8d48988d1a8941735",
"name":"General College & University",
"pluralName":"General Colleges & Universities",
"shortName":"Other - Education",
"icon":"https:\/\/foursquare.com\/img\/categories\/education\/default.png",
"parents":[
"Colleges & Universities"
],
"primary":true
}
],
"verified":false,
"stats":{
"checkinsCount":5,
"usersCount":4,
"tipCount":0
},
"hereNow":{
"count":0
}
}
]
}
]
}
}
i want to use icon to show icon in imageview. please suggest me how can i get this icon value and how can i user this icon url in imageview.
Thank you in advance.
i am trying this, but still it is creating error:-
this is my code:- but still is creating error:-
JSONArray groups= (JSONArray) jsonObj.getJSONObject("response").getJSONArray("groups");
int length= groups.length(); if (length > 0){ for (int i = 0; i < length; i++)
{
JSONObject group= (JSONObject) groups.get(i); JSONArray items =(JSONArray) group.getJSONArray("items");
for (int j = 0; j < items.length(); j++)
{
JSONObject item = (JSONObject) items.get(j);
JSONObject iconobject=(JSONObject) item.getJSONObject("categories");//this is creating error that JSON.typeMismatch
venue.icon=iconobject.getString("icon");
}}}}
The class JSONObject can help you:
String data = ... // your json data
JSONObject json = new JSONObject(data);
You can access nodes in your structure with help of getJSONObject(String) and getJSONArray(String).
For example:
JSONObject response = json.getJSONObject("response");
JSONArray groups = response.getJSONArray("groups");
JSONObject firstGroup = groups.getJSONObject(0);
// and so on
When you got your node that contains your icon value you can use the getString(String) method to get the icon url:
JSONObject firstCategory = categories.getJSONObject(0);
String iconUrl = firstCategory.getString("icon");
After you got the url you have to download the image before you can use it. How to download an image from an url is described here
When you downloaded the image you can update the imageview:
Bitmap image = loadBitmap(iconUrl); // how to implement loadBitmap is shown in the link above
ImageView iv = findViewById(R.id.my_imageview);
iv.setImageBitamp(image);
Try this:
try {
JSONArray jArray = new JSONArray(result);
// get into the 'groups' array
JSONObject jData = jArray.getJSONObject(0);
JSONArray jGroupsArray = jData.getJSONArray("groups");
// get into the 'items' array
jData = jArray.getJSONObject(2);
JSONArray jItemsArray = jData.getJSONArray("items");
// get into the 'categories' array
jData = jArray.getJSONObject(4);
JSONArray jCategoriesArray = jData.getJSONArray("categories");
// get into the 'icon' value as String and use it as you please
jData = jArray.getJSONObject(4);
String iconURL = jData.getString("icon");
} catch (JSONException e) {
Log.e(Constants.LOG_TAG, "Error parsing data", e);
}
Hope this helps
Refer to the JSON documentation: http://www.json.org/javadoc/org/json/package-summary.html. It's really simple.
In your case, you would have to read the JSON string to a JSON object, then parse "response" as a JSONObject, "groups" as a JSONArray inside "response", iterate through the JSONObjects contained in the "groups" array, parse "Items" as a JSONArray inside your JSONObject, and son on...
You should be able to get to the URL in no time.