82

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.

soufrk
  • 825
  • 1
  • 10
  • 24
AKIWEB
  • 19,008
  • 67
  • 180
  • 294
  • 2
    `android.jar` only contains stubs to compile against. To run, you need the full library. – obataku Aug 09 '12 at 00:01
  • Yes I imported `android.jar` in my project.. Can you point me from where I can download the full library? – AKIWEB Aug 09 '12 at 00:06

7 Answers7

96

See my comment. You need to include the full org.json library when running as android.jar only contains stubs to compile against.

In addition, you must remove the two instances of extra } in your JSON data following longitude.

   private final static String JSON_DATA =
     "{" 
   + "  \"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\""
   + "    }" 
   + "  ]" 
   + "}"; 

Apart from that, geodata is in fact not a JSONObject but a JSONArray.

Here is the fully working and tested corrected code:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ShowActivity {


  private final static String JSON_DATA =
     "{" 
   + "  \"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\""
   + "    }" 
   + "  ]" 
   + "}"; 

  public static void main(final String[] argv) throws JSONException {
    final JSONObject obj = new JSONObject(JSON_DATA);
    final JSONArray geodata = obj.getJSONArray("geodata");
    final int n = geodata.length();
    for (int i = 0; i < n; ++i) {
      final JSONObject person = geodata.getJSONObject(i);
      System.out.println(person.getInt("id"));
      System.out.println(person.getString("name"));
      System.out.println(person.getString("gender"));
      System.out.println(person.getDouble("latitude"));
      System.out.println(person.getDouble("longitude"));
    }
  }
}

Here's the output:

C:\dev\scrap>java -cp json.jar;. ShowActivity
1
Julie Sherman
female
37.33774833333334
-121.88670166666667
2
Johnny Depp
male
37.336453
-121.884985
Community
  • 1
  • 1
obataku
  • 29,212
  • 3
  • 44
  • 57
  • Thanks veer. I opened that link but I couldn't find the jar file to download. Can you point me to exact location from where I can download it. – AKIWEB Aug 09 '12 at 00:09
  • 3
    @Nevzz03 try [here](http://repo1.maven.org/maven2/org/json/json/20090211/json-20090211.jar). – obataku Aug 09 '12 at 00:10
  • I did as per your suggestion. I downloaded the jar also, imported into our project too. And when I ran my project, I got exception as- `Exception in thread "main" org.json.JSONException: JSONObject["geodata"] is not a JSONObject. at org.json.JSONObject.getJSONObject(JSONObject.java:596) at com.niharika.testing.JsonTest.main(JsonTest.java:31) ` Any thoughts will be appreciated. – AKIWEB Aug 09 '12 at 00:19
  • @Nevzz03 I have posted fully working code now. Let me know how it works out for you. – obataku Aug 09 '12 at 00:22
  • Thanks a lot veer. Really appreciate all your help!! – AKIWEB Aug 09 '12 at 00:29
  • @Nevzz03 no problem dude! Glad I could help :-) Note you won't need the *json.jar* when deploying via Android. – obataku Aug 09 '12 at 00:30
  • 2
    The link to org.json is dead. However, The example also works with [JSON-Java](https://github.com/stleary/JSON-java). I only had to move the files, according to the referred package, to a newly created folder `org/json/`. – Monkey Supersonic Sep 15 '16 at 18:38
6

To convert your JSON string to hashmap you can make use of this :

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;

Use this class :) (handles even lists , nested lists and json)

public class Utility {

    public static Map<String, Object> jsonToMap(Object json) throws JSONException {

        if(json instanceof JSONObject)
            return _jsonToMap_((JSONObject)json) ;

        else if (json instanceof String)
        {
            JSONObject jsonObject = new JSONObject((String)json) ;
            return _jsonToMap_(jsonObject) ;
        }
        return null ;
    }


   private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }


    private static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }


    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }
        return list;
    }
}

Natesh bhat
  • 12,274
  • 10
  • 84
  • 125
4

credit to this blog This answer may help someone whose requirements are different.

This is your Json string

 {
"pageNumber":20,
"pageTitle":"example page title",
"pageInfo": {
        "pageName": "Homepage",
        "logo": "https://www.example.com/logo.jpg"
},
"posts": [
        {
            "post_id": "0123456789",
            "actor_id": "1001",
            "author_name": "Jane Doe",
            "post_title": "How to parse JSON in Java",
            "comments": [],
            "time_of_post": "1234567890"
        }
    ]
}

and this is how to read it

 import org.json.JSONArray;
 import org.json.JSONObject;

 public class ParseJSON {
 static String json = "...";
 public static void main(String[] args) {

    JSONObject obj = new JSONObject(json);
    String pageTitle = obj.getString("pageTitle");
    String pageNumber= obj.getInt("pageNumber");
    String pageName =      obj.getJSONObject("pageInfo").getString("pageName");

    System.out.println(pageNumber);
    System.out.println(pageTitle );
    System.out.println(pageName);

    JSONArray arr = obj.getJSONArray("posts");
    for (int i = 0; i < arr.length(); i++) {
        String post_id = arr.getJSONObject(i).getString("post_id");
        System.out.println(post_id);
    }
  }
}
Odwori
  • 1,460
  • 13
  • 14
3

Looks like for both of your objects (inside the array), you have an extra closing brace after "Longitude".

Aaron Kurtzhals
  • 2,036
  • 3
  • 17
  • 21
2

Firstly there is an extra } after every array object.

Secondly "geodata" is a JSONArray. So instead of JSONObject geoObject = jObject.getJSONObject("geodata"); you have to get it as JSONArray geoObject = jObject.getJSONArray("geodata");

Once you have the JSONArray you can fetch each entry in the JSONArray using geoObject.get(<index>).

I am using org.codehaus.jettison.json.

JHS
  • 7,761
  • 2
  • 29
  • 53
2

Here is the example of one Object, For your case you have to use JSONArray.

public static final String JSON_STRING="{\"employee\":{\"name\":\"Sachin\",\"salary\":56000}}";  
try{  
   JSONObject emp=(new JSONObject(JSON_STRING)).getJSONObject("employee");  
   String empname=emp.getString("name");  
   int empsalary=emp.getInt("salary");  

   String str="Employee Name:"+empname+"\n"+"Employee Salary:"+empsalary;  
   textView1.setText(str);  

}catch (Exception e) {e.printStackTrace();}  
   //Do when JSON has problem.
}

I don't have time but tried to give an idea. If you still can't do it, then I will help.

1

you have an extra "}" in each object, you may write the json string like this:

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\""            
    + "                }" 
    + "        }" 
    + "    ]" 
    + "}"; 
}
Divyesh Kanzariya
  • 3,629
  • 3
  • 43
  • 44
Prog Mania
  • 615
  • 9
  • 14
  • @Nevzz03 you may use [link](http://flexjson.sourceforge.net/)flexjson java lib to create you json object instead. – Prog Mania Aug 09 '12 at 00:06