I am parsing some json in an app and I have come across arrays that sometimes have information in it:
{
"output": [
{
"id": "1521",
"name": "Apples",
}
]
}
and sometimes has nothing. e.g
{
"output": [
[]
]
}
I was parsing it by
JSONArray output = c.getJSONArray("output");
int outputLength = output.length();
for (int q = 0; q < outputLength; q++)
{
JSONObject d = outputs.getJSONObject(q);
id[q] = d.getInt("id");
name[q] = d.getString("name");
}
but when it gets to the empty array it crashes.
I get the following error then:
01-19 01:08:00.237: W/System.err(17627): org.json.JSONException: Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject
it crashes because it's trying to convert the jsonarray into an object and you can't do that so I tried getting the first array in output with:
JSONArray add = output.getJSONArray(0);
but that will crash as well because in the first output it's an object in it and not an array.
I don't have access or control over the json feed and I'm stuck at the moment as to how to parse the result.
The real answer is: "Fix whatever is generating that horrible JSON".
If that's not an option you're going to have to figure out exactly what you have before trying to access it. The JSONArray.optJSONObject() method can help with this; it returns null if the specified index doesn't contain a JSONObject:
JSONArray output = c.getJSONArray("output");
for (int q = 0; q < outputLength; q++)
{
JSONObject d = output.optJSONObject(q);
if (d != null)
{
id[q] = d.getInt("id");
name[q] = d.getString("name");
}
}
Because you're parsing everything in the enclosing JSONArray as aJSONObject, all the entries would have to be formatted that way. For that to work, your source string would have to look like this:
[
{
"output": [
{
"id": "1521",
"name": "Apples"
}
]
},
{
"output": [
[]
]
}
]
Everything in the top-levelJSONArray is now a JSONObject and can be parsed accordingly. What's inside of those objects is your business (empty arrays are OK). A good resource for checking if a given JSON string is valid is this website.
Related
I'm tried to parse some json array (with string and two-dimensional array) into objects array, but the solutions I found do not work (or I was looking bad).
Please, help me with the code to get an array of objects.
I found working method for Java (I tried it in Eclipse) this,
but I want it for Android (in Android Studio)
My json file:
[
{
"someString": "First string",
"someTwoDimArray":
[
["First_firstElement", "First_secondElement"],
[true, false]
]
},
{
"someString": "Second string",
"someTwoDimArray":
[
["Second_firstElement", "Second_secondElement"],
[true, true]
]
}
]
I have java class:
public class someClass {
String someString;
Object[][] someTwoDimArray;
}
What I need: (To process the data in the code later)
someClass[] someClasses = /* ??? */
Try something like this:
JSONArray jsonarray = new JSONArray(jsonStr);
int L = yourArrayWithJSON.length();
first = new String[L];
second = new String[L];
third = new String[L];
for (int i = 0; i < L; i++) {
JSONObject point = vpn.getJSONObject(i);
first[i] = point.getString("first");
second[i] = point.getString("second");
third[i] = point.getString("third");
String url = jsonobject.getString("url");
}
Ask, if you have any questions
On Android, I am retrieving a JSON object via the following method;
JSONObject tempObj = jsonObj.getJSONArray("result");
In order to be sure it comes properly, I system out it;
System.out.println(tempObj);
And it gives the following output;
{
"result": [
{
"telMobile": "5555555",
"products": [
{
"id": "113245",
"price": "749.0",
"unitId": 1
},
{
"id": "52589",
"price": "7.35",
"unitId": 1
}
]
}
]
}
So, the JSONObject tempObj has a JSONArray named "products" inside, and each product has three fields named "id", "price" and "unitId". However, when I parse this object, I receive a "no value for unitId" error.
for (int k = 0; k < tempObj.getJSONArray("products").length(); k++) {
JSONObject tempProduct = tempObj.getJSONArray("products").getJSONObject(k);
products.add(new Product(tempProduct.getString("id"), tempProduct.getString("price"),tempObj.getInt("unitId")));
}
This is totally senseless. I can obtain the other fields properly. That means when I don't retrieve the unitId and write 1 instead;
for (int k = 0; k < tempObj.getJSONArray("products").length(); k++) {
JSONObject tempProduct = tempObj.getJSONArray("products").getJSONObject(k);
products.add(new Product(tempProduct.getString("id"), tempProduct.getString("price"),1));
}
Then the object is constructed properly. I tried getting it as a String then converting to int as;
Integer.parseInt(tempProduct.getString("unitId"));
However unitId still gives error. I would think that there would be a problem on the server side but the JSONObject arrives properly since I can see it from logcat output. This is a simple integer how can it cause such an arror? Could there be lying some different problems behind such a case?
You should change
tempObj.getInt("unitId")
to
tempProduct.getInt("unitId")
Actually you're trying to get value from tempObj. That is wrong. There is no value. so instead of get value from tempProduct
unitId is part of tempProduct not of tempObj.
Change
tempObj.getInt("unitId")))
with
tempProduct.getInt("unitId")))
So I have a json response from web service like this
{
error: false
types: [2]
-0: {
card_type_id: 5
category: "Food & Beverages"
}
-1: {
card_type_id: 8
category: "Entertaiment"
}
}
what I want to do is to get the number inside json array "types" and use it to looping to set the value of arraylist that will be use in listview, but my code seems and cannot get the json array length, this is my code
JSONObject obj = new JSONObject(response);
if(!obj.getBoolean("error")){
JSONArray types = obj.getJSONArray("types");
for(int i=0; i<types.length();i++)
{
JSONObject a = types.getJSONObject(i);
int ct_id = a.getInt("card_type_id");
String category = a.getString("category");
CardType ct = new CardType();
ct.setTypeId(_ct_id);
ct.setTypeCategory(_category);
categoryArray.add(ct);
}
}
Can anyone help me? Thanks before
This is what your JSON response probably should look like (note also that keys and string values should be sorrounded by double-quotes):
{
"error": false,
"types": [
{
"card_type_id": 5,
"category": "Food & Beverages"
},
{
"card_type_id": 8,
"category": "Entertaiment"
}
]
}
The JSONArray "types" in this example has a length (types.length()) of 2. Now you can implement your for-loop and should get the expected results.
actually it's just my fault to see the json from advanced rest client, i use the json menu and the app automatically correct the json and become invalid, after i change to raw menu i can see the actual json and correct the code
1.I am having json object like this how can i get the access to all values in android
2.before anyone down voting that i want to say i have searched stackoverflow for similar examples but those examples contains JSONObject and then JSONArray
3.Here in my case everything is JSONObject so i'm little bit confused
{
"1":
{"sno":"10","latitude":"31.249441437085455","longitude":"75.70003598928452"},
"2":
{"sno":"11","latitude":"31.249398442090207","longitude":"75.70003397762775"}
}
This is how i made it to JSONObject
1.Below code returned me output like that which is all JSONObject
2.Is there any way to make "1" and "2" as JSONArray ?
$select_rows = "select sno,latitude,longitude from activities where username='$username'";
if ($result = mysql_query($select_rows)) {
$num_of_fields = mysql_num_fields($result);
$num_of_rows = mysql_num_rows($result);
$i = 0;
$j = 1;
while ($retrieved = mysql_fetch_array($result)) {
for ($i = 0; $i < $num_of_fields; $i++) {
$field_name = mysql_field_name($result, $i);
$object[$j][$field_name] = $retrieved[$field_name];
}
$j++;
}
echo json_encode($object);
}
Hope this may help you
JSONObject jsonObject=new JSONObject(result);
jsonObject=jsonObject.getJSONObject("1");
Double lat=jsonObject.getDouble("latitude");
Toast.makeText(getBaseContext(),""+ lat, Toast.LENGTH_LONG).show();
Better create a valid JSONArray to make things easier. When you create the JSON string , don't append the index. I believe your are reading the data from sqlite and generating the JSON string.
Also change the outer { (curly brace) to [ (square bracket) to represent as Array element. So your json string will be like this
[
{
"sno": "10",
"latitude": "31.249441437085455",
"longitude": "75.70003598928452"
},
{
"sno": "11",
"latitude": "31.249398442090207",
"longitude": "75.70003397762775"
}
]
Then , you can simply get its as JSONArray
JSONArray jsonArray = new JSONArray(jsonString);
And then read each element in array item
for(int index = 0;index < jsonArray.length(); index++) {
JSONObject jsonObject = jsonArray.getJSONObject(index);
}
To get one of your inner JSONObject elements, you'll need to get it from the outer one using getJSONObject(String key).
Sample code:
JSONObject item1 = myJson.getJSONObject("1");
//item1 now contains {sno:10,latitude:31.2...etc}
//now you can get the individual values out of the resulting JSON Object
//for example, getting the latitude
double lat = item1.getDouble("latitude");
I have a JSON as shown below:
{
"places": [{
"name": "Ankola",
"slug": "ankola",
"category": "beach",
"distance": "521",
"travel_time": "8 hrs, 2 mins",
"days": "3",
"latitude": "14.669456",
"longitude": "74.300952",
"weather": "Summer 21\u00b0-36\u00b0C, Winter 12\u00b0-35\u00b0C",
"todo": "Baskal gudda, Nadibag, Shedikuli, Keni, Belekeri",
"about": "Ankola is a small town surrounded by numerous temples. It is in line with Arabian sea. Ankola is famous for its native breed of mango called ishaad and for cashews harvesting.",
"image": [
"Cm5NXlq.jpg",
"9OrlQ9C.jpg",
"DRWZakh.jpg",
"dFKVgXA.jpg",
"5WO2nDf.jpg"
]
}]
}
I know how to fetch key - value pairs, but i dont know how to parse array inside json to form a string array(image - in my case)
To summarize i want something like this:
I have 5 image names under "image" tag, i want them in a string array. How can i do this?
Use :
JSONArray images = yourJSONObject.getJSONArray("image");
for(int i = 0; i < images.length(); i++){
String image = images.getString(i);
}
This should do the trick as I remember.
Here you go:
JSONArray ja = whatEverYourJsonObject.getJSONArray("image");
for(int i=0; i<ja.length(); j++){
String name = ja.getString(i);
}
You first have to convert the JSON string to a Java object (JSONObject). Then, you obtain your JSONArray and iterate over it.
Example:
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject (jsonString);
JSONArray images = itemObj.getJSONArray ("images");
int length = images.length ();
for (int i = 0; i < length; i++)
Log.d ("Image Filename", images.getString (i));
} catch (JSONException e) {
e.printStackTrace();
}
EDIT: Now I see that your JSON is invalid - you have an object for each image and that object contains only the value part of the data. An example of a valid images array would be as follows:
{
"image": [
"Cm5NXlq.jpg",
"9OrlQ9C.jpg",
"DRWZakh.jpg",
"dFKVgXA.jpg",
"5WO2nDf.jpg"
]
}
I would suggest:
Create your own class which describes your data structure defined
by those json object. As a last resort you can even generate Java
class based on JSON string - look at
jsongen
When you will have your own Java class (let's say MyClass) you can easily parse JSON to your generated Java class using GSON, like:
MyClass myClass = gson.fromJson(jsonString, MyClass.class);