I'm able to parse nested json string with ObjectMapper
class. The problem here is it's getting difficult to parse the nested json as I had to write lot of boilerplate code to achieve the end result of parsing json to java objects. Is there any better way of parsing in spring other than this approach?
Domain classes :
Components class
public class Components {
private String name;
private String url;
private List<Properties> properties;
// getters and setters
}
properties class :
public class Properties {
private String name;
private String value;
private boolean exclusions;
// getters and setters
}
Controller class:
@RestController
public class TempController {
String jsonResponse = null;
@RequestMapping("/")
public @ResponseBody String getResponse(){
JsonreadApplication ja = new JsonreadApplication();
jsonResponse = ja.readJsonFile();
//System.out.println(jsonResponse);
return jsonResponse;
}
@RequestMapping("/temp")
public @ResponseBody String getTempByServerType(String jsonResponse){
jsonResponse = getResponse();
Components components = new Components();
ObjectMapper objectMapper = new ObjectMapper();
try {
Iterator<Entry<String, JsonNode>> fieldNames = objectMapper.readTree(jsonResponse).fields();
while(fieldNames.hasNext()){
System.out.println(fieldNames.next());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "I've parsed json!";
}
}
json file :
{
"name": "CatalogTools",
"url": "/atg/commerce/catalog/CatalogTools/",
"properties": [
{
"name": "queryASAFFabrics",
"value": "skuType=\"ASAF_FABRIC\" AND NOT basicColor IS NULL ORDER BY dynamicAttributes.fabricpriceband, basicColor, dynamicAttributes.fabrictype, dynamicAttributes.asafpattern, dynamicAttributes.asaffabricbrand",
"exclusions": "false"
},
{
"name": "loggingDebug",
"value": "true",
"exclusions": "false"
}
]
}
As said earlier, parsing can be done with ObjectMapper
instance but with lot of boilerplate code and hardcoding json element names. Is there a better way of doing this? I'm using jackson
library to parse the json file.
I've referred many links online where @RequestBody
annotation was used for HTTP POST
operations. Here, it is a HTTP GET
request.
Any help is highly appreciated.
Many Thanks in advance.