2017-06-30 39 views
0

我需要消耗RESTAPI,这给了我这个样子Spring MVC的 - 从外部JSON

{ 
"id": "e5d5ccc0-8da4-430d-b0ec-096d17ae2af8", 
"car": [ 
{ 
    "identifier": "XX000YY", 
    "formattedAddress": "Address 1", 
    "lat": 45.841664, 
    "lng": 18.199905, 
    "isOn": false, 
    "odometer": 763.4, 

} 
], 
"location": "92589f4a-8c6e-4494-8548-b5428f8fa598" 
} 

一个JSON输出。通常我会创建一个包装对象得到的只是一个单一的对象

public class Wrapper{ 

private String id; 

private Car car; 

private String location; 

//getters and setters 

} 

然后在我的控制,我会做这样的

RestTemplate restTemplate = new RestTemplate(); 
ResponseEntity<Wrapper> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity,wrapper); 

东西,得到的回应

但基本上我只需要Car对象,所以我想如果有一种方法只返回它,而不是整个包装的,并从中

+0

https://stackoverflow.com/questions/38866411/how-to-get-specific-对象从-resttemplate交换法 –

回答

2

首先服用Car对象,你必须创建一个序列化的对象是这样的:

Car.java

package com.wrapper; 


public class Car implements Serializable{ 

public String identifier; 
public String formattedAddress; 
public Float lat; 
public Float lng; 
public Boolean isOn; 
public Float odometer; 

} 

Wrapper.java

package com.wrapper; 

import java.util.List; 

public class Wrapper implements Serializable{ 

public String id; 
public List<Car> car = null; 
public String location; 

} 

之后,使用谷歌API GSON和使用该指令获取对象:

Wrapper wrapper = gson.fromJson(response, Wrapper.class);