I am trying to parse a JSON string in java to have the individual value printed separately. But while making the program run I get the following error-
Exception in thread "main" java.lang.RuntimeException: Stub!
at org.json.JSONObject.<init>(JSONObject.java:7)
at ShowActivity.main(ShowActivity.java:29)
My Class looks like-
import org.json.JSONException;
import org.json.JSONObject;
public class ShowActivity {
private final static String jString = "{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " }"
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " }"
+ " ]"
+ "}";
private static JSONObject jObject = null;
public static void main(String[] args) throws JSONException {
jObject = new JSONObject(jString);
JSONObject geoObject = jObject.getJSONObject("geodata");
String geoId = geoObject.getString("id");
System.out.println(geoId);
String name = geoObject.getString("name");
System.out.println(name);
String gender=geoObject.getString("gender");
System.out.println(gender);
String lat=geoObject.getString("latitude");
System.out.println(lat);
String longit =geoObject.getString("longitude");
System.out.println(longit);
}
}
Let me know what is it I am missing, or the reason why I do get that error everytime I run the application. Any comments would be appreciated.
Here is the example of one Object, For your case you have to use JSONArray.
I don't have time but tried to give an idea. If you still can't do it, then I will help.
Firstly there is an extra
}
after everyarray object
.Secondly "geodata" is a
JSONArray
. So instead ofJSONObject geoObject = jObject.getJSONObject("geodata");
you have to get it asJSONArray geoObject = jObject.getJSONArray("geodata");
Once you have the
JSONArray
you can fetch each entry in theJSONArray
usinggeoObject.get(<index>)
.I am using
org.codehaus.jettison.json
.Looks like for both of your objects (inside the array), you have an extra closing brace after "Longitude".
To convert your JSON string to hashmap you can make use of this :
Use this class :) (handles even lists , nested lists and json)
you have an extra "}" in each object, you may write the json string like this:
Correct me if i'm wrong, but json is just text seperated by ":", so just use
keep using st.nextToken() until you're out of data. Make sure to use "st.hasNextToken()" so you don't get a null exception.