如何从json转换为java对象?

时间:2015-03-11 11:10:35

标签: java json gson

我有一个get请求,json的响应如下:

{"version": 0.6,
 "generator": "Overpass API",
  "osm3s": {
  "timestamp_osm_base": "",
   "copyright": "The data included in this document is from  www.openstreetmap.org. The data is made available under ODbL."
 },
 "elements": [

{
 "type": "node",
 "id": 25941318,
 "lat": 35.7006285,
 "lon": 51.3909900
  },
 {
  "type": "node",
   "id": 26839944,
   "lat": 35.7006369,
   "lon": 51.3913739
    },
  {
   "type": "node",
   "id": 1333387625,
   "lat": 35.7012370,
   "lon": 51.3913564
    }

    ]
  }

我需要将这个Json转换为java对象, 这是我的模特课:

package com.findItntersection.model;

public class Intersection {

String type;

private long id;

private double lon;

private double lat;

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public double getLon() {
    return lon;
}

public void setLon(double lon) {
    this.lon = lon;
}

public double getLat() {
    return lat;
}

public void setLat(double lat) {
    this.lat = lat;
}

@Override
public String toString() {

      return "elements [ type=" + type + ",id=" + id + ",lon=" + lon +
      ".lat" + lat + "]";

}}

和我正确发送get请求的服务方法:

public void sendGet(String city, String street1, String street2)
        throws ClientProtocolException, IOException, URISyntaxException {

    Gson gson = new Gson();

    URIBuilder builder = new URIBuilder();
    builder.setScheme("http")
            .setHost("192.168.0.67")
            .setPath("/api/interpreter")
            .setParameter(
                    "data",
                    "[out:json];area[name~\""
                            + city
                            + "\"]->.b;way(area.b)[highway][name~\""
                            + street1
                            + "\"];node(w)->.n1;way(area.b)[highway][name~\""
                            + street2 + "\"];node(w)->.n2;node.n1.n2;out;");

    URI uri = builder.build();

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(uri);
    CloseableHttpResponse response1 = httpclient.execute(httpGet);

    try {
        System.out.println(response1);
        HttpEntity entity1 = response1.getEntity();

        String json = EntityUtils.toString(entity1,"UTF-8");


        Intersection fromJson = gson.fromJson(json, Intersection.class);
        System.out.println(fromJson);
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }
}

但是fromJson是这样的: [type = null,id = 0,lon = 0.0.lat0.0]

来自get request json的结果:

{
 "version": 0.6,
  "generator": "Overpass API",
   "osm3s": {
   "timestamp_osm_base": "",
   "copyright": "The data included in this document is from   www.openstreetmap.org. The data is made available under ODbL."
   },
  "elements": [

 {
  "type": "node",
   "id": 29004231,
   "lat": 35.7212341,
   "lon": 51.3888708
    }

    ]
   }

有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:1)

那是因为您的回复不是Intersection。它是一个包含Intersections

数组的对象

因此,您首先需要将JSON转换为JsObject,然后获取此数组并将其转换为List of Intersections

String json = EntityUtils.toString(entity1,"UTF-8");

JsonParser jp = new JsonParser();

JsonObect jo = ( JsonObject ) jp.parse( json );

// JsonArray of intersection JsonElement's
JsonArray ija = ( JsonArray ) jo.get( "elements" );

// Iterator of intersection JsonElements
Iterator<JsonElement> iji = ija.iterator();

List< Intersection> il = new ArrayList< Intersection >();

while( iji.hasNext() ) {
    JsonElement je = iji.next();
    // convert to Intersection
    Intersection i = gson.fromJson( je, Intersection.class );
    // add to List
    il.add( i );
}

// do whatever you want with your list of intersections.

答案 1 :(得分:1)

Gson无法解析,因为您的回复不是Intersection类的表示。

它代表了类似的东西:

public class OsmResult implements Serializable{
    private double version;
    private String generator;
    private HashMap<String, String> osm3s;
    private ArrayList<Intersection> elements;

    ...getters & setters
}

从这里开始,您可以采取两种方式;

  
      
  1. 提取elements并将其解析为Intersection列表。
  2.   

我认为Gson中没有提取方法,但您可以尝试其他Json库。或者,您可以执行简单的字符串操作来提取elements

  
      
  1. 将其解析为上述类,只需使用getElements()方法。
  2.   

如果你坚持使用Gson,我建议你这样做更清洁。

答案 2 :(得分:0)

这是因为您的模型类不正确。 类交集只是映射json中的元素。 你应该有一个模型类,用于映射所有json元素,使用&#34; Elements&#34;作为另一个定义自己元素的类。

http://www.journaldev.com/2324/jackson-json-processing-api-in-java-example-tutorial

这个例子应该有所帮助。

相关问题