2016-08-25 4 views
0

Я хочу создать запрос endepoints с использованием весенней загрузки: мне нужно потреблять успокоительный api и преобразовывать его в другую конечную точку отдыха.Получите данные как формат JSON весной загрузки

У меня есть ответ на JSon www.exampleapiurl.com/details

[{ 
     "name": "age", 
     "value": "Child" 
    }, 
{ 
     "name": "recommendable", 
     "value": true 
    }, 

{ 
     "name": "supported", 
     "value": yes 
    }, 
] 
[{ 
     "name": "age", 
     "value": "Adult" 
    }, 
{ 
     "name": "recommendable", 
     "value": true 
    }, 

{ 
     "name": "supported", 
     "value": no 
    }, 
] 

Я хочу, чтобы ответ будет:

[{ 
     "age": "Child" 
    }, 
{ 
     "recommendable": true 
    }, 

{ 
     "supported": "yes" 
    }, 
] 
[{ 
     "age": "Adult" 
    }, 
{ 
     "recommendable": true 
    }, 

{ 
     "supported": "no" 
    }, 
] 

Для этого у меня есть класс атрибута с геттер и сеттер: Attributes.class

@JsonIgnoreProperties(ignoreUnknown = true) 
public class Attributes { 
private String age; 
private boolean recommendable; 
private String supported; 

getter and setter for these: 
} 

Это мой service.java класс

@Service 
public class CService { 
    private static RestTemplate restTemplate; 
    public String url; 

    @Autowired 
    public CService(String url) { 
     this.url = url; 
    } 

    public Attributes getAttributes() { 

     HttpHeaders headers= new HttpHeaders(); 
     headers.add("Authorization", "some value"); 
     HttpEntity<String> request = new HttpEntity<String>(headers); 
     ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, Attributes.class); 
     return response.getBody(); 

    } 
} 

И это мой controller.class

@Controller 
public class CController { 
    private CService cService; 
    @Autowired 
    public CController(CService cService) { 
     this.cService = cService; 
    } 

    @RequestMapping(value="/example") 
    @ResponseBody 
    public Attributes getCAttributes() { 
     return cService.getAttributes(); } 

} 

авторизация успешно, но, я не получаю никакого ответа на данный момент

+0

Глядя на ваш код , две вещи, которые я могу сказать с первого взгляда. 1) Если вы хотите получить ответ как тип атрибута, тогда ResponseEntity response = restTemplate.exchange (url, HttpMethod.GET, request, Attributes.class); должен быть изменен как ResponseEntity response = restTemplate.exchange (url, HttpMethod.GET, request, Attributes.class); 2) Вы хотите получить ответ в виде массива, но логически ваш код не возвращает массив –

+0

yes, а класс responsetype, который я даю здесь, немного отличается. я хочу, чтобы tp дал общий класс json и проанализировал этот класс json и соответствующим образом отобразил атрибуты ... любая идея –

ответ

0

Что вы можете сделать, это создать класс модели для получить ответ от примера API следующим образом.

@JsonIgnoreProperties(ignoreUnknown = true) 
public class Details{ 
    private String name; 
    private String value; 

    @JsonProperty("value") 
    public String getValue() { 
     return value; 
    } 
    public void setValue(String value) { 
     this.value = value; 
    } 

    @JsonProperty("name") 
    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 
} 

Затем измените вызывающую код RestTemplate следующим

 Details[] details = null; 
//Keeps the example API's data in array. 


     ResponseEntity<Details[]> response = restTemplate.exchange(url, HttpMethod.GET, request, Details[].class); 
      details = response.getBody(); 

// Следующий шаг обработать этот массив и отправить ответ обратно к клиенту

List<Attributes> attributes = new ArrayList<Attributes>(); 
    Attributes attr = null; 
    for(Details detail : details) { 
     attr = new Attributes(); 
     //set the values here 
    } 

//returns the attributes here 
attributes.toArray(new Attributes[attributes.size()]);