我当前正在研究一个项目,在该项目中,我需要对外部API进行休息,并将JSON响应解析为POJO,然后将POJO返回为JSON,以获得另一个REST请求。我能够解析JSON响应,但我的要求是从中仅解析一个特定的节点。我该如何实现?我正在使用Spring Boot和Spring Rest模板进行外部休息调用。请帮忙!
@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"
}
使用org.json
库。借助此库,您可以将有效载荷解析为jsonobject,并导航到您所需的文档子部分。
因此,您必须将有效载荷作为JSON-String
获取,然后将其从库中解析为JSONObject
。之后,您可以导航到文档的所需子部分,然后提取值,然后将其解析为所需的Java Pojo。
看过:如何解析JSON
只需将路径映射到所需的对象:
{
"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();