在Java中解析JSON字符串

2j4z5cfb  于 2022-11-27  发布在  Java
关注(0)|答案(7)|浏览(333)

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

让我知道我错过了什么,或者为什么我每次运行应用程序时都会得到这个错误。任何评论都将不胜感激。

7vhp5slm

7vhp5slm1#

看我的评论。当运行 android时,你需要包括完整的org.json library。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
2vuwiymt

2vuwiymt2#

要将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;
    }
}
w41d8nur

w41d8nur3#

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

hmae6n7t

hmae6n7t4#

this blog这个答案可能会帮助那些要求不同的人。
这是Json字符串

{
"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"
        }
    ]
}

这是如何阅读它

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

tuwxkamq5#

首先,在每个array object之后有一个额外的}
其次,“geodata”是一个JSONArray。因此,您必须将其获取为JSONArray geoObject = jObject.getJSONArray("geodata");,而不是JSONObject geoObject = jObject.getJSONObject("geodata");
一旦有了JSONArray,就可以使用geoObject.get(<index>)来获取JSONArray中的每个条目。
我使用的是org.codehaus.jettison.json

bwitn5fc

bwitn5fc6#

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

我没时间,但我想给你出个主意,如果你还是做不到,那我就帮你。

fnx2tebb

fnx2tebb7#

如果在每个对象中有一个额外的“}”,您可以这样编写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\""            
    + "                }" 
    + "        }" 
    + "    ]" 
    + "}"; 
}

相关问题