I have a JSONArray from net.minidev.json which I want to convert to List<HashMap<String,Object>>.
There are many answers for converting the JSONArray using Gson.
However, I cannot add Gson as a dependency to my pom.xml, so I am looking for a way to achieve it with Java-8 features.
My JSONArray is something like this: It comprises multiple hierarchies.
[
{
"data": {
"name": "idris"
},
"children": [
{
"processStandardDeduction": 69394,
"cropId": 1,
"data": null,
"expectedQuantityPerAcre": 1220,
"name": "Red Tomato 1 quality",
"id": 1003,
"autoArchivePlotDays": 59902
},
{
"processStandardDeduction": 69394,
"cropId": 1,
"autoArchivePlotDays": 59902
},
{
"processStandardDeduction": 69394,
"cropId": 1,
"autoArchivePlotDays": 59902
}
],
"name": "Red Tomato",
"id": 1002
},
{
"data": null,
"name": "Red Tomato 1 quality",
"id": 1003,
"processStandardDeduction": 69394,
"cropId": 1,
"expectedQuantityPerAcre": 1220,
"cropName": "Tomato",
"autoArchivePlotDays": 59902
},
{
"data": null,
"name": "Red Tomato 3 quality",
"id": 1001,
"processStandardDeduction": 69394,
"autoArchivePlotDays": 59902
},
{
"processStandardDeduction": 69394,
"cropId": 1,
"data": null,
"id": 1004,
"autoArchivePlotDays": 59902
}
]
I would like to achieve same structure in List>
I tried looping each element of the JSONArray by converting it to each HashMap<String,Object> and then adding it to the List<HashMap<String,Object>>.
ObjectMapper mapper = new ObjectMapper();
List<HashMap<String, Object>> cropDetailsList = new ArrayList<>();
for (Object eachCropJson : cropDetails) { //cropDetails is the JSONArray
HashMap<String, Object> eachCropMap = (HashMap<String, Object>) mapper.convertValue(eachCropJson,
HashMap.class);
cropDetailsList.add(eachCropMap);
}
return cropDetailsList;
I would like to try a better approach using Java-8 features without using a forEach. Thanks in advance.
mapand collecting should workcropDetails.stream().map(eachCropMap -> (Map<String, Object>) mapper.convertValue(eachCropJson, HashMap.class)).collect(Collectors.toList())