I've been looking extract image urls from the Flickr api for my android application.
More specifically, I need to parse the first owner and first id field for the following JSON
http://pastebin.com/NVKXdELx
Hence, I tried
JSONObject json = new JSONObject(jsonString);
JSONObject photos = json.getJSONObject("photos");
JSONObject photo = photos.getJSONObject("photo");
String picOwner = photo.getString("owner");
String picID = photo.getString("id");
To me, the logic makes sense (grab the row photos, then grab the row photo, then extract the owner field as a string). However, an error is thrown on
JSONObject photo = photos.getJSONObject("photo");
Am I overlooking something?
Note: The ultimate values I am looking for are
"id": "8637130199",
"owner": "93693022#N07"
The element identified by "photo" is a JSON Array, you need to use the JSONArray class
JSONObject json = new JSONObject(jsonString);
JSONObject photos = json.getJSONObject("photos");
JSONArray photo = photos.getJSONArray("photo");
if (photo.length() > 0) {
JSONObject first = photo.getJSONObject(0);
String picOwner = first.getString("owner");
String picID = first.getString("id");
}
Related
i m trying to get values from JSONArray inside array, i m able to retrieve whole JSON values into JSONArray successfully but not able to retrieve values inside JSONArray. When i convert JSONArray to JSONObject to get values stored inside JSONArray. It gives error: org.json.JSONException: No value for "banner"
Here is JSON code, i verified JSON code with jsonlint.com and it showed JSON is Validate,
[
{"code":"banner","moduletitle":0,
"banner":
[
{"image":"http://imageurl"},
{"image":"http://imageurl"},
{"image":"http://imageurl"}
]
}
]
I m trying to get this from 3 hour but no luck. i m new in JSON and do not know how JSON Actually work, and also read abut GSON Library to get JSON values. here is My Java code.
JSONArray jsonObj = null;
String image_url = "";
String banner_code ="";
try {
jsonObj =new JSONArray(lib_function.getJSONUrl( jsontags.Top_Banner_JOSN_URLs));
Log.d("value retrun :","" +jsonObj);
//---vlaue is coming and print in Log ----//
} catch (JSONException e) {
Log.v("Error in Parser :", " " + e);
Log.d("no value retrun :", "failed to convert");
}
try{
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName", jsonObj);
JSONArray subArray = jo.getJSONArray("banner");
image_url= subArray.getString(Integer.parseInt("image"));
Log.d("banner code",""+subArray);
}catch(Exception e)
{
Log.d("not working",""+e);
}
I folllow this question but luck:
How to parse JSON Array inside another JSON Array in Android
If anyone suggest, what i m doing wrong will be appreciate. or let me know, where i can get more information about json
UPDATE thanks too all to give their precious time for answering my stupid question. All answers are correct , but i can accept only one answer. A Big thanks to all
Here:
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName", jsonObj);
Because parsing jsonObj JSONArray so no need to create new JSONArray and JSONObject to extract it from jsonObj. remove all above three lines.
banner JSONArray is inside JSONObject which is contained by jsonObj JSONArray, get it as:
JSONObject jsonObject=jsonObj.optJSONObject(0);
JSONArray subArray = jsonObject.getJSONArray("banner");
// get code key from `jsonObject`
String strCode=jsonObject.optString("code");
// get all images urls from `subArray`
for(int index=0;index<subArray.length();index++){
JSONObject imgJSONObject=subArray.optJSONObject(index);
// get image urls
String strImgURL=imgJSONObject.optString("image");
}
Also, if jsonObj JSONArray contains multiple JSONObject's then use for-loop to iterate it.
I am assuming you have the rest of the values accessible to you, so posting just this snippet.
code=jsonObject.getString("code");
moduletitle=jsonObject.getString("moduletitle");
banner=jsonObject.getJSONArray("banner");
jsonObj =new JSONArray(lib_function.getJSONUrl( jsontags.Top_Banner_JOSN_URLs);
From above line you will get JSONArray. So now loop it and get you banner JSONArray.Again loop bannerArray and you will get image Urls
If You want value of "image" which is in json arrray than
String response = "your response";
try{
JsonArray jAry = new JsonArray(response);
JsonObject jObj = jAry.getJsonObject(0);
JsonArray jsonBanner = jObj.getJsonArray("banner");
JsonObject temp;
for(int i=0;i<jsonBanner.length;i++){
temp = jsonBanner.getJsonObject(i);
String image = temp.optString("image");
}
}
I am working on Yahoo Finance. Trying to parse json data from a url, such as Google finance data.
I am fetching data into a string "str" and then parsing the json data to reach the name field inside resources.
the json data is :
{
"list":{
"meta":{
"type":"resource-list",
"start":0,
"count":1
},
"resources":[
{
"resource":{
"classname":"Quote",
"fields":{
"name":"Alphabet Inc.",
"price":"710.489990",
"symbol":"GOOGL",
"ts":"1452891600",
"type":"equity",
"utctime":"2016-01-15T21:00:00+0000",
"volume":"3833751"
}
}
}
]
}
}
I am trying to use this code, but it is not working - need to reach the "name" field:
str4 = Client.execute(httpget, responseHandler);
//str holds the json data given above- checked.
JSONObject str1 = new JSONObject(str4);
JSONObject list = str1.getJSONObject("list");
JSONArray resources = list.getJSONArray("resorces");
JSONObject fields = resources.getJSONObject(1);
str2 = fields.getString("name");
I notices three issues with your code:
you have one item in your JSONArray, so you should retrieve item 0, not item 1.
you misspelled the word resources in your code.
Also, I think you didn't retrieve the fields correctly. This should do it:
JSONObject str1 = new JSONObject(str4);
JSONObject list = str1.getJSONObject("list");
JSONArray resources = list.getJSONArray("resources");
JSONObject fields = resources.getJSONObject(0).getJSONObject("resource").getJSONObject("fields");
str2 = fields.getString("name");
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");
}
}
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.
I'm trying to use the JSON library to consume twitter information from the get search feature. I'm getting the error:
A JSONArray text must start with '[' at 1 [character 2 line 1]
So it's basically in the wrong form. Some people are saying this needs to be an object but everytime I call the constructor it says that it can't take a String as input. How do I get this string into the form of a JSONArray so that I can access it's elements.
Here is my code:
URL twitterSource = new URL("http://search.twitter.com/search.json?q=google");
ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream();
IOUtils.copy(twitterSource.openStream(), urlOutputStream);
String urlContents = urlOutputStream.toString();
// parse JSON
System.out.println(urlContents);
JSONArray jsonArray = new JSONArray(urlContents);
// use
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.getString("id"));
System.out.println(jsonObject.getString("text"));
System.out.println(jsonObject.getString("created_at"));
}
my print statement shows the string contains:
{"completed_in":0.318,"max_id":144850937012428800,"max_id_str":"144850937012428800","next_page":"?page=2.....................
This is a string in the form of a JSON object but it is not actually an object. It's still a string. I'm printing a String. HOw can I get this into an Object or better yet a JSONArray so that I can actually access its elements.
That's a JSON object, not an array.