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.
Related
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");
From my server is get a JSON response like this:
String json = getJsonFromServer();
The server returns this reply (with the double quotes in the beginning and end):
"{\"error\":\"Not all required fields have been filled out\"}";
I then want to get the error field. I have tried to use the JSONObject class to get the string, but it does not work.
System.out.println("The error is: " + new JSONObject().getJSONObject(response).getString("error");
I have try
String response = "{\"error\":\"Not all required fields have been filled out\"}";
JSONParser parser = new JSONParser();
try {
JSONObject json = (JSONObject) parser.parse(response);
System.out.println(json.get("error").toString());
} catch (ParseException ex) {
}
It have working, you can try it and don't forget add json lib json-simple
You seem to be using the wrong JSONObject constructor; in your example, you are trying to fetch an object from a newlay created object - it will never exist.
Try this:
String response = "{\"error\":\"Not all required fields have been filled out\"}";
JSONObject json = new JSONObject( response );
String error = json.getString( "error" );
System.out.println( error );
Yields
Not all required fields have been filled out
edit
Now that you have completely changed the question...
Why not just first strip the first and last char?
So if
String response = "\"{\"error\":\"Not all required fields have been filled out\"}\"";
response = response.substring(1, response.length() - 1));
// Now convert to JSONObject
Your response object has exactly this string?
{"error":"Not all required fields have been filled out"}
The code below printed the expected output:
Object responseObject = "{\"error\":\"Not all required fields have been filled out\"}";
JSONObject jsonObject = new JSONObject(responseObject.toString());
String errorContent = jsonObject.getString("error");
System.out.println(errorContent);
I am trying to make an android app that fetch posts from my wordpress blog that displays the information in a list. I am able to get the results like title, description,etc but i am not able to get nested object "tags" from the JSON result. So, can you explain me how i can get the tag names from the JSON result from this JSON Response.
I am trying to use the following code :
JSONObject root = new JSONObject(postJSON);
JSONArray postsArray = root.getJSONArray("posts");
for (int i = 0; i < postsArray.length(); i++) {
// Get a single post at position i within the list of earthquakes
JSONObject currentPost = postsArray.getJSONObject(i);
String title = currentPost.getString("title");
Log.e(LOG_TAG, "title is " + title);
JSONObject tags = currentPost.getJSONArray("tags").getJSONObject(0);
String tag = tags.getString("name");
Log.e(LOG_TAG, "tag is " + tag);
Post post = new Post(title,"123", tag);
posts.add(post);
}
But the logcat is showing that the value can't be converted to JSONArray.
The issue is that tags is actually another JSON object not a JSON array. You need to do the following:
JSONObject tags = currentPost.getJSONObject("tags").getJSONObject(0);
String tag = tags.getString("name");
Log.e(LOG_TAG, "tag is " + tag);
Just remember JSON arrays are always denoted by [] and objects by {}.
Hope this helps.
I am trying to get json data from a fake api call and need to get the count of the items in it(so that in future I can call the actual restful service). I am not able to get the number of departments in the json. I am expecting the result as 4(int) here.
I am not able to get the string value(json) for the code below:
String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class);
Please find below the entire code:
String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class);
JSONObject jsnobject = new JSONObject(json);
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
JSON Sample:
{
"Department":
[
{"SectionId":"1","SectionName":"Childrens Wear"},
{"SectionId":"2","SectionName":"Womens Wear"},
{"SectionId":"3","SectionName":"F&A"},
{"SectionId":"1","SectionName":"Mens Wear"}
]
}
I am new to java as well as api's.
Thanks,
You are either using incorrect key in code or you posted incorrect JSON example. You used locations as the key incode however there is no value against that key in sample JSON. You need to use Department as the key.
JSONArray jsonArray = jsnobject.getJSONArray("Department");
In my android project, I have an activity in which I want to obtain data from database using a PHP script. I manage the result of the script in this line :
String result = EntityUtils.toString(entity);
I created the jsonObject :
JSONObject jsonObject = new JSONObject(result);
I print this line and get: {"id":"1"}{"id":"2"}{"id":"3"}
But when I do this:
int i;
for(i=0;i<array.length;i++)
{
array[i] = "ID : "+jsonObject.getString("id");
}
I obtain "id : 1" three times, so I think there are some errors in the cycle..
the code of script php is here :
#Get the first row of the results
while ($row = mysqli_fetch_row($data)) {
#Build the result array (Assign keys to the values)
$result_data = array(
'id' =>$row[0],
);
#Output the JSON data
echo json_encode($result_data);
change to:
int i;
for(i=0;i<array.length;i++)
{
jsonObject=array[i];
String s = "ID : "+jsonObject.getString("id");
}
{"id":"1"}{"id":"2"}{"id":"3"}
is no valid code for a single JSON object - see here: JSON syntax.
I can only guess what you try to achieve, but I would guess your intention is to have a JSON array with 3 objects, each having an "id" value. The JSON code for such a structure should look like this:
[{"id":"1"},{"id":"2"},{"id":"3"}]
If you can make "EntityUtils.toString(entity)" to return the above JSON code, the following loop should also work:
JSONArray ja = new JSONArray(result);
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
System.out.println("ID : "+jsonObject.getString("id"));
}
edit
On a side note: I believe you get the result you describe, because when you call
new JSONObject(result);
where the result is a String that consists of
{"id":"1"}{"id":"2"}{"id":"3"}
then most likely JSONObject stops parsing the JSON code after the first right brace without throwing a parse exception. So it actually only parses the first JSON object and because of this you get "id : 1" three times. Personally I would consider this behavior a bug, so consider reporting it.