76

我正在尝试在 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);                   
   }
}

让我知道我缺少什么,或者每次运行应用程序时都会出现该错误的原因。任何意见将不胜感激。

4

8 回答 8

90

见我的评论。您需要在运行时包含完整的org.json 库,因为android.jar仅包含要编译的存根。

此外,您必须删除}JSON 数据后面的两个 extra 实例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实际上不是 aJSONObject而是 a 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
于 2012-08-09T00:06:53.343 回答
5

要将您的JSON 字符串转换为 hashmap,您可以使用以下命令:

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

于 2018-07-01T08:17:09.060 回答
2

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

于 2012-08-09T00:01:58.133 回答
1

}首先,在 each之后有一个额外的array object

其次,“地理数据”是一个JSONArray. 因此,JSONObject geoObject = jObject.getJSONObject("geodata");您必须将其作为JSONArray geoObject = jObject.getJSONArray("geodata");

拥有 后,JSONArray您可以获取JSONArrayusing中的每个条目geoObject.get(<index>)

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

于 2012-08-09T00:07:02.323 回答
1

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

我没有时间,但试图给出一个想法。如果你还是做不到,那我来帮忙。

于 2017-07-26T16:48:34.737 回答
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\""            
    + "                }" 
    + "        }" 
    + "    ]" 
    + "}"; 
}
于 2012-08-09T00:04:56.177 回答
0

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

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

参考如何将 JSON 转换为 Java 对象 Gson 示例/从 Java 对象 Gson 示例

于 2021-06-12T18:19:25.823 回答
-5

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

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

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

继续使用 st.nextToken() 直到数据用完。确保使用“st.hasNextToken()”,以免出现空异常。

于 2012-08-09T00:01:32.217 回答