Android - How to extract nested value from JSON string - java

This is my String gathered from a JSON file. It is as expected:
{
"catalog":{
"book":{
"id":"bk101",
"author":"Gambardella, Matthew",
"title":"XML Developer's Guide",
"genre":"Computer",
"price":"44.95",
"publish_date":"2000-10-01",
"description":"An in-depth look at creating applications with XML."
}
}
}
Using this String I created a JSONObject..
JSONObject jsonBook = new JSONObject(sb.toString());
Then I am simply trying to extract some of the parameters seen in the string such as id and author.
"id": "bk101"` `"author": "Gambardella, Matthew"
This is my approach..
book.setAuthor(jsonBook.getString(Book.AUTHOR));
book.setId(jsonBook.getString(Book.ID));
Yet I keep getting errors saying there is no value for id/author whichever one is first. Any ideas?
Cheers

That's because id and author are both inside book, not inside the json root
JSONObject jsonBook = new JSONObject(sb.toString());
JSONObject catalogue = jsonBook.getJSONObject("catalog");
JSONObject jbook = catalogue.getJSONObject("book");
book.setAuthor(jbook.getString(Book.AUTHOR));
book.setId(jbook.getString(Book.ID));

Related

How to search a specific part of a JSON object and add to an already existing object

I'm new to using JSONs and I'm having a bit of difficulty. I am using the Kitsu API and parsing the JSON I get when I login. When I parse my json the image below pops up, but inside the 1 object array I want to get the large url in the avatar object inside of the attributes object and I don't know how.The beginning of the JSON, The middle of the JSON, The end. Lastly, I want to know how to edit the slug part of the JSON, if you don't know that's cool the main thing is getting the avatar url.
Picture of my error
Please, try this...
JSONObject myObject = new JSONObject(jsonStr);
JSONArray myArray = myObject.getJSONArray("data");
JSONObject obj = myArray.getJSONObject(0);
String id = obj.getString("id");
String type = obj.getString("type");
//change the lines bellow
JSONObject attributes = obj.getJSONObject("attributes");
JSONObject avatar = attributes.getJSONObject("avatar");
String large = avatar.getString("large");

How can I print a json string?

I'm doing a school project (newbie alert) where I need to use the zomato's website to get a cuisine's ID and name depending on the ID I send. This is the code in the demo file:
WebServiceConnection web = new WebServiceConnection("xxxxxxxxxxxx");
AcessoDados acesso = new AcessoDados("https://api.zomato.com/v1/cuisines.json", web);
String aces = acesso.getCuisines(310);
JSONObject obj = new JSONObject();
System.out.println(obj.get(aces));
All the methods called here were made by our teacher.
WebServiceConnection and AcessoDados function get the link to Zomato's API and the user key. (Zomato API requires a key to work)
"acesso.getCuisines(310)" sends the the value "310", and the method "getCuisines" should return a json string with all the establishments it can find in their website (310 is the ID for Porto, Portugal).
However, it only prints "[]" in the output (without the quotes). It should print something like this:
[
{"cuisine_name":"African","cuisine_id":152},
{"cuisine_name":"American","cuisine_id":1},
{"cuisine_name":"Angolan","cuisine_id":951},
{"cuisine_name":"Cafe","cuisine_id":30},
(...)
]
I can't find what the problem is or if I'm making any obvious mistake. Am I missing something here?
If System.out.println(aces); prints [], then Zomato's API is returning an empty response, which means that 310 is not a valid id. But, if aces prints a non-empty string and is a JSON String then the following solution should work.
You are not parsing the JSON string which was received by Zomato API. Instead, you are creating a new JSONObject which is empty.
Try doing the following :
JSONObject obj = null;
try {
obj = (JSONArray) JSONValue.parseWithException(aces);
System.out.println(obj);
} catch (ParseException e) {
e.printStackTrace();
}
Assumptions :
You are using json-simple

Insufficient Data getting Parsed in the Facebook Graph API

I am trying to get facebook feeds of a page. When I open this link in browser, the full json appears with no problem but when I parse it using following code only the first two posts get displayed in app.
url = "https://graph.facebook.com/v2.2/awaaziitkgp/feed?access_token="
+ static_token;
for parsing, i am doing this
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_DATA);
String x = null;
Log.d("contact.length", x.valueOf(contacts.length()));
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String message = c.getString(TAG_MESSAGE);// feed
String createtime = c.getString(TAG_CREATETIME);// date,
// time
Log.d("POSTS", message); // created
The first two json objects are getting parsed correctly, but the rest are not visible.
I have found the solution. The problem was is JSON file. Some of the posts didn't contain message field, that's why on third post due to no "message" field, JSONObject returned empty and terminated the loop.
I'd added if (c.has("message") == true)before getting data from message field to avoid null JSONObject.
Two of your JSONObjects are getting parsed without any problem. I think the field "message" that you are searching is not available in your third object.
Check you JSON properly. Hope it helps.

How to consume/deserialize .Net WCF service JSON response in Java

I am having problem while consuming/deserializing WCF .NET JSON response in Java. JSON response is in the following format.
{"d":"[
{\"ID\":123,\"Company\":\"Microsoft\",\"Country\":\"USA\",
\"website\":\"http:\/\/www.microsoft.com\",
\"FirstName\":\"john\",\"Email\":\"abc#gmail.com\"},
{\"ID\":124,\"Company\":\"Google\",\"Country\":\"USA\",
\"website\":\"http:\/\/www.google.com\",
\"FirstName\":\"john\",\"Email\":\"abc#gmail.com\"},
{\"ID\":125,\"Company\":\"Apple\",\"Country\":\"USA\",
\"website\":\"http:\/\/www.abc.com\",
\"FirstName\":\"john\",\"Email\":\"abc#gmail.com\"}
]"}
While on the Java code side I am having problem to deserialize this json response to get out my objects and their corresponding properties.
This is the java code currently I am using to deserialize json response.
String companyTitle = "";
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonResponseString);
if (element.isJsonObject()) {
JsonArray companies = element.getAsJsonArray();
JsonObject company = companies.get(0).getAsJsonObject();
companyTitle = company .get("Company").getAsString();
}
Is there any problem in the JSON response format or its right? any kind of help is appreciated, thanks in advance.
I'm not sure why you're getting that response - it't not valid json. There are two things wrong with it
The outer square brackets should not be wrapped in quotes.
The quote escape characters need to be removed (not sure if this is just you putting them in?)
Without you posting the actual error you get (hint: even though stack overflow is powerful, we have not yet developed the ability to read minds) it's very difficult to know what the actual problem is.
Tom is right. Valid JSON should look like this:
{"d":[
{"ID":123,"Company":"Microsoft","Country":"USA",
"website":"http://www.microsoft.com",
"FirstName":"john","Email":"abc#gmail.com"},
{"ID":124,"Company":"Google","Country":"USA",
"website":"http://www.google.com",
"FirstName":"john","Email":"abc#gmail.com"},
{"ID":125,"Company":"Apple","Country":"USA",
"website":"http://www.aabc.com",
"FirstName":"john","Email":"abc#gmail.com"}
]}
And your code like this:
String companyTitle = "";
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonResponseString);
JsonObject object = element.getAsJsonObject();
if (object.isJsonObject()) {
JsonArray companies = object.getAsJsonArray("d");
JsonObject company = companies.get(0).getAsJsonObject();
companyTitle = company .get("Company").getAsString();
}

Extracting JSON fields using java

I am trying to extract a person's details who liked a facebook page by passing the page id as parameter. I extracted the JSON content of that page and now from that I want to extract name and id of users.
How do I achieve that ?
Code:
JSONObject json = readurl("https://graph.facebook.com/pageid");
System.out.println(json.toString());
System.out.println("Page id is:"+json.get("id"));
JSON:
"likes":{
"data":[
{
"id":"*******",
"name":"vv"
},
{
"id":"********",
"name":"abc"
},
Code like this would do the trick.
JSONObject json = readurl("https://graph.facebook.com/pageid");
JSONArray dataJsonArray = json.getJSONArray("data");
for(int i=0; i<dataJsonArray.length; i++) {
JSONObject dataObj = dataJsonArray.get(i);
String id = dataObj.getString("id");
//Similarly you can extract for other fields.
}
Basically data is a JSONArray since it starts with [. So simply get would not work, you must use JSONArray.
Note: I haven't compiled this code, but I think I gave you idea to proceed. Also refer this link to get hold of basics of parsing JSON in java.
This snippet is not tested, but I'm pretty sure it works:
JSONArray data = json.getJSONArray("data");
for (int i=0; i < data.length(); i++) {
JSONObject o = data.getJSONObject(i);
sysout(o.getString("id");
sysout(o.getString("name");
}
I use google's Gson library from: https://code.google.com/p/google-gson/

Categories

Resources