Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON string in Java

Tags:

java

json

parsing

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.

like image 223
AKIWEB Avatar asked Aug 08 '12 23:08

AKIWEB


People also ask

What is JSON parsing in Java?

JSON stands for JavaScript Object Notation, and it is based on a subset of JavaScript. As a data-exchange format, it is widely used in web programming. Here we show how to parse JSON in Java using the org. json library. A JSON object is an unordered set of key/value pairs.

What is JSON string in Java?

The json. simple library allows us to read and write JSON data in Java. In other words, we can encode and decode JSON object in java using json.

How do I parse JSON in Java w3schools?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

How do you escape a JSON string in Java?

You can escape String in Java by putting a backslash in double quotes e.g. " can be escaped as \" if it occurs inside String itself. This is ok for a small JSON String but manually replacing each double quote with an escape character for even a medium-size JSON is time taking, boring, and error-prone.


2 Answers

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 
like image 76
obataku Avatar answered Oct 04 '22 11:10

obataku


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

like image 32
Natesh bhat Avatar answered Oct 04 '22 11:10

Natesh bhat