且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Java 中解析 JSON 字符串

更新时间:2023-02-17 09:51:58

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

See my comment. You need to include the full org.json library when running as android.jar only contains stubs to compile against.

此外,您必须删除 JSON 数据中 longitude 后面的两个额外 } 实例.

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

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

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

输出如下:

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