在Java中解析JSON字符串

时间:2012-08-08 23:52:46

标签: java json parsing

我正在尝试解析java中的JSON字符串,以单独打印单个值。但在运行程序时,我收到以下错误 -

Exception in thread "main" java.lang.RuntimeException: Stub!
       at org.json.JSONObject.<init>(JSONObject.java:7)
       at ShowActivity.main(ShowActivity.java:29)

我的班级看起来像 -

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

让我知道我错过了什么,或者每次运行应用程序时我都会遇到错误的原因。任何意见将不胜感激。

8 个答案:

答案 0 :(得分:68)

查看我的comment。 运行时需要包含完整的org.json library android.jar 只包含要编译的存根。

此外,您必须在}之后的JSON数据中删除额外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\""
   + "    }" 
   + "  ]" 
   + "}"; 

除此之外,geodata实际上不是JSONObject而是JSONArray

以下是完整工作且经过测试的更正代码:

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

这是输出:

C:\dev\scrap>java -cp json.jar;. ShowActivity
1
Julie Sherman
female
37.33774833333334
-121.88670166666667
2
Johnny Depp
male
37.336453
-121.884985

答案 1 :(得分:4)

要将您的 JSON字符串转换为哈希图,您可以使用

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

使用此类:)(甚至处理列表,嵌套列表和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;
    }
}

答案 2 :(得分:2)

对于两个对象(在数组内)看起来,在“经度”之后你有一个额外的右括号。

答案 3 :(得分:1)

首先,每}之后还有一个额外的array object

其次“地理数据”是JSONArray。因此,您需要JSONObject geoObject = jObject.getJSONObject("geodata");

而不是JSONArray geoObject = jObject.getJSONArray("geodata");

获得JSONArray后,您可以使用JSONArray获取geoObject.get(<index>)中的每个条目。

我正在使用org.codehaus.jettison.json

答案 4 :(得分:0)

每个对象中都有一个额外的“} ”, 你可以写这样的json字符串:

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

答案 5 :(得分:0)

我们将使用 java 对象打印 json 的值。我们可以使用 Gson 库将 json 字符串解析为 java 对象。我们有一个 json 字符串,如

   String json = "{"id":1,"name" : "json" }"

现在我们将 json 字符串解析为 java 对象,所以首先我们创建带有文件名 id 和 name 的 java pojo

public class Student {
private int id;
private String  name;
     //getter 
    //setter
 }

我们将使用 Gson 从 json 字符串创建学生对象

 Student stu = gson.fromJson(json, Student.class);

现在您可以使用 getter 打印任何 json 字段的值

     System.out.println(" id ="+ stu.getId() +" name ="+ stu.getName());

参考How to convert JSON to / from Java Object Gson Example

答案 6 :(得分:-1)

以下是一个Object的示例,对于您的情况,您必须使用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.
}

我没有时间,但试图提出一个主意。如果你仍然无法做到,那我就会帮忙。

答案 7 :(得分:-2)

如果我错了,请纠正我,但json只是用“:”分隔的文字,所以只需使用

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

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

继续使用st.nextToken(),直到数据不足为止。确保使用“st.hasNextToken()”,这样就不会出现空异常。