如何从 json 转换为 java 对象?

how to Convert from json to java object?

我有一个 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 对象, 这是我的模型 class:

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请求的结果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
    }

    ]
   }

有人可以帮我吗?

这是因为您的模型class不正确。 Class 交集只是映射 json 中的元素。 您应该有一个模型 class,它映射所有 json 元素,"Elements" 作为另一个 class 定义它自己的元素。

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

这个例子应该有所帮助。

那是因为您的回复不是 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.

Gson 无法解析,因为您的响应不是 Intersection class.

的表示

它代表的是这样的东西:

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

    ...getters & setters
}

从这里开始,你可以走两条路;

  1. Extract elements and parse it to a Intersection list.

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

  1. Parse it to a class like above and just use getElements() method.

如果您坚持使用 Gson,我建议您使用它,因为它更简洁。