我目前正在开发一个项目,我需要对外部API进行休息调用,并将JSON响应解析为POJO,并将POJO作为JSON返回给另一个休息请求。我能够解析JSON响应,但我的要求是只从中解析一个特定节点。我怎样才能实现这一目标?我使用Spring Boot和Spring Rest Template进行外部休息呼叫。请帮忙!!!
@RestController
public class ProductsController {
private static final Logger LOGGER = LoggerFactory.getLogger(ProductsController.class);
@RequestMapping(value = "/myRetail/product/{id}", method = RequestMethod.GET, produces = {
MediaType.APPLICATION_JSON_UTF8_VALUE, MediaType.APPLICATION_XML_VALUE })
@ResponseBody
public Item getSchedule(@Valid Payload payload) {
String URL = "<External API>";
LOGGER.info("payload:{}", payload);
Item response = new Item();
RestTemplate restTemplate = new RestTemplate();
Item item = restTemplate.getForObject(URL, Item.class);
LOGGER.info("Response:{}", item.toString());
return response;
}
}
JSONResponse (This is a part of whole i receive)
{
"ParentNode": {
"childNode": {
"att": "13860428",
"subchildNode 1": {
"att1": false,
"att2": false,
"att3": true,
"att4": false
},
"att4": "058-34-0436",
"att5": "025192110306",
"subchildenode2": {
"att6": "hello",
"att7": ["how are you", "fine", "notbad"],
"is_required": "yes"
},
............
}
Required JSONpart from the above whole response:
"subchildenode2": {
"att6": "hello",
"att7": ["how are you", "fine", "notbad"],
"is_required": "yes"
}
答案 0 :(得分:0)
使用JSON-String
库。使用此库,您可以将有效负载解析为JSONObject并导航到文档所需的子部分。
因此,您必须将有效负载作为JSONObject
并将其解析为库中的spyOn
。之后,您可以导航到文档所需的子部分并提取值,然后将其解析为所需的Java POJO。
答案 1 :(得分:0)
只需将路径映射到所需对象:
{
"ParentNode": {
"childNode": {
"subchildenode2": {
"att6": "hello",
"att7": ["how are you", "fine", "notbad"],
"is_required": "yes"
}
}
}
然后简单地说:
Response responseObject= new Gson().fromJson(json, Response.class);
SubChildNode2 att6 = responseObject.getParentNode().getChildNode().getSubChildNode2();