简体   繁体   English

在 Java 中解析 JSON 字符串

[英]Parsing JSON string in Java

I am trying to parse a JSON string in java to have the individual value printed separately.我正在尝试在 java 中解析 JSON 字符串以单独打印单个值。 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.任何意见将不胜感激。

See my comment .见我的评论 You need to include the full org.json library when running as android.jar only contains stubs to compile against.您需要在运行时包含完整的org.json 库,因为android.jar仅包含要编译的存根。

In addition, you must remove the two instances of extra } in your JSON data following longitude .此外,您必须删除 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\""
   + "    }" 
   + "  ]" 
   + "}"; 

Apart from that, geodata is in fact not a JSONObject but a JSONArray .除此之外, geodata实际上不是JSONObject而是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

To convert your JSON string to hashmap you can make use of this :要将您的JSON 字符串转换为 hashmap ,您可以使用以下命令:

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

Use this class :) (handles even lists , nested lists and json)使用这个类: )(处理偶数列表、嵌套列表和 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;
    }
}

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

Firstly there is an extra } after every array object .首先,每个array object之后都有一个额外的}

Secondly "geodata" is a JSONArray .其次“地理数据”是一个JSONArray So instead of JSONObject geoObject = jObject.getJSONObject("geodata");所以代替JSONObject geoObject = jObject.getJSONObject("geodata"); you have to get it as JSONArray geoObject = jObject.getJSONArray("geodata");你必须把它作为JSONArray geoObject = jObject.getJSONArray("geodata");

Once you have the JSONArray you can fetch each entry in the JSONArray using geoObject.get(<index>) .拥有JSONArray后,您可以使用geoObject.get(<index>)获取JSONArray中的每个条目。

I am using org.codehaus.jettison.json .我正在使用org.codehaus.jettison.json

Here is the example of one Object, For your case you have to use JSONArray.这是一个对象的示例,对于您的情况,您必须使用 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.如果你还是做不到,那我来帮忙。

you have an extra " } " in each object, you may write the json string like this:你在每个对象中有一个额外的“ } ”,你可以这样写 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\""            
    + "                }" 
    + "        }" 
    + "    ]" 
    + "}"; 
}

We will print value of json using java object.我们将使用 java 对象打印 json 的值。 We can parse json string to java object using Gson library.我们可以使用 Gson 库将 json 字符串解析为 java 对象。 We have one json string like我们有一个 json 字符串,例如

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

Now we will parse json string to java object , So first we create java pojo with filed name id and name现在我们将 json 字符串解析为 java 对象,所以首先我们创建带有文件名 id 和 name 的 java pojo

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

We will create student object from json string using Gson我们将使用 Gson 从 json 字符串创建学生对象

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

Now you can print value of any filed of json using getter现在您可以使用 getter 打印任何 json 字段的值

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

Reference : How to convert JSON to / from Java Object Gson Example参考如何将 JSON 转换为/从 Java 对象 Gson 示例

credit to this blog This answer may help someone whose requirements are different.归功于此博客此答案可能会对要求不同的人有所帮助。

This is your Json string这是你的 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"
        }
]

} }

and this is how to read it这就是如何阅读它

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

} }

Correct me if i'm wrong, but json is just text seperated by ":", so just use如果我错了,请纠正我,但 json 只是由“:”分隔的文本,所以只需使用

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.继续使用 st.nextToken() 直到数据用完。 Make sure to use "st.hasNextToken()" so you don't get a null exception.确保使用“st.hasNextToken()”,以免出现空异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM