[java] Parsing JSON string in Java

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.

This question is related to java json parsing

The answer is


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\""            
    + "                }" 
    + "        }" 
    + "    ]" 
    + "}"; 
}

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.


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 :

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;
    }
}


Correct me if i'm wrong, but json is just text seperated by ":", so just use

String line = ""; //stores the text to parse.

StringTokenizer st = new StringTokenizer(line, ":");
String input1 = st.nextToken();

keep using st.nextToken() until you're out of data. Make sure to use "st.hasNextToken()" so you don't get a null exception.


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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to parsing

Got a NumberFormatException while trying to parse a text file for objects Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Python/Json:Expecting property name enclosed in double quotes Correctly Parsing JSON in Swift 3 How to get response as String using retrofit without using GSON or any other library in android UIButton action in table view cell "Expected BEGIN_OBJECT but was STRING at line 1 column 1" How to convert an XML file to nice pandas dataframe? How to extract multiple JSON objects from one file? How to sum digits of an integer in java?