如何将这个json数据解析为java

时间:2011-09-30 07:15:42

标签: json parsing geometry

这是json代码..我是json解析的新手。所以请让我知道如何将这个json数据解析为java。 提前谢谢!!

  {
     "geometry" : {
        "location" : {
           "lat" : 13.0561990,
           "lng" : 80.2348820
        }
     },
     "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
     "id" : "cf67cea9c203824f58eaf5abe98a08912593bf90",
     "name" : "Mahalingapuram Branch",
     "reference" : "CnRsAAAAlAu76wP4EspUn8qk6yUBndsDI7RaEmDaXHc2gP1bomAP_22ZeswWfj3ganEwX9jO2BYjRo6eoeKlwrSeMNDv5h94zqnsNncDntlKN_MqC-gegTBZLX5YxOSA-vzuk6bKe3BJlHytW_wKJJs0Nxf3jRIQT1yYWTlDdMhk9EyS8ulMghoUZK5J51RRVKo12LPdHm_qCQWX_VA",
     "types" : [ "establishment" ],
     "vicinity" : "Mahalingapuram Main Road, Nungambakkam, Chennai"
  }

在此解析java代码后发生错误

public static void main(String[] args) throws Exception{
    InputStream is = JsonParsing.class.getResourceAsStream( "");
    String jsonTxt = IOUtils.toString( is );
    JSONObject json = (JSONObject)JSONSerializer.toJSON(jsonTxt);   
    JSONObject html_attribution = json.getJSONObject(“html_attribution");
    JSONObject geometry= json.getJSONObject(“geometry”);
    JSONObject location= json.getJSONObject(“location”);

    double latitude = json.getDouble("latitude");
    double longitude = json.getDouble("longitude");
    String icon= result.getString("icon");
    String id = result.getString("id");
    String reference= result.getString("reference");
    String name = result.getString("name");
    String vicinity = result.getstring("vicinity");

    System.out.println("html_attribution: " + html_attribution);
    System.out.println("location: " + location);
    System.out.println(“latitude: “ + latitude);
    System.out.println(“latitude: “ + longitude);
    System.out.println("result: " + result);
}

4 个答案:

答案 0 :(得分:2)

我使用以下内容:

http://code.google.com/p/google-gson/

序列化为JSON:

Gson gson = new GsonBuilder().create(); 
String jsonOutput = gson.toJson(someObject);

从JSON反序列化:

BagOfPrimitives obj = gson.fromJson(json, BagOfPrimitives.class);

可在此处找到用户指南:

https://sites.google.com/site/gson/gson-user-guide

答案 1 :(得分:1)

使用http://www.json.org/中的java库。

答案 2 :(得分:1)

看看GSON Google project。它是一个库,可以让您将所有JSON数据转换为Java对象。它很简单。

答案 3 :(得分:0)

JSONObject geometry = json.getJSONObject("geometry");

JSONObject location = json.getJSONObject("location");

String lat = location.getString("lat");
String lng = location.getString("lng");

icon = json.getString("icon");

id = json.getString("id");

name = json.getString("name");

reference = json.getString("reference");

vicinity = json.getString("vicinity");

JSOnArray types = json.getJSONArray("types");

for (int i=0;i<=types.length();i++)
{

JSonObject temJson = (JSONObject) types.get(i);

String Varialb = temJson.get(i);

}