I'm trying to deserialize the following JSON
to a java object.
"distance":[
{
"weight": 60,
"unit": "km"
},
{
"weight": 100,
"unit": "m"
}
]
The java object should look like:
[
{
"km": 60
},
{
"m": 100
}
]
Here I have found two issues, One, it is not well formed JSON. It should be:
{
"distance":[
{
"weight": 60,
"unit": "km"
},
{
"weight": 100,
"unit": "m"
}
]
}
OR
[
{
"weight": 60,
"unit": "km"
},
{
"weight": 100,
"unit": "m"
}
]
Another is, you did not mention your POJO clearly. You can achieve this response several ways. For simplicity I am assuming simple Map
for it.
However, we need to make this string well formed at first.
String jsonStr = "\"distance\":[\n" +
" {\n" +
" \"weight\": 60,\n" +
" \"unit\": \"km\"\n" +
" },\n" +
" {\n" +
" \"weight\": 100,\n" +
" \"unit\": \"m\"\n" +
" }\n" +
"]";
jsonStr = jsonStr.substring(jsonStr.indexOf(":") + 1);
Create a class:
@Data
public class Distance {
private Double weight;
private String unit;
}
Here I have used lombok for getter and setter.
Parse JSON string to list of Distance
:
ObjectMapper objectMapper = new ObjectMapper();
List<Distance> distances = objectMapper.readValue(jsonStr, new TypeReference<List<Distance>>(){});
Now you can convert this list to your desired response. For converting this response to Map
:
Map<String, Double> response = distances.stream().collect(Collectors.toMap(Distance::getUnit, Distance::getWeight));
OR, you can convert it to List<Pair<String, Double>>
as well:
List<Pair<String, Double>> response = new ArrayList<>();
distances.forEach(distance -> {
response.add(new Pair(distance.getUnit(), distance.getWeight()));
});
Happy coding...
The problem can be solved using JSONObject and HashMap
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Main {
public static void main(String args[]) throws JSONException {
ArrayList<HashMap<String, Double>> result = new ArrayList<HashMap<String,Double>>();
String jsonStr = "{\n" +
" \"distance\": [\n" +
" { \n" +
" \"weight\": 60, \n" +
" \"unit\": \"km\" \n" +
" }, \n" +
" { \n" +
" \"weight\": 100, \n" +
" \"unit\": \"m\" \n" +
" } \n" +
" ]\n" +
"}";
JSONObject json = new JSONObject(jsonStr);
JSONArray distanceArray = json.getJSONArray("distance");
for(int i = 0; i < distanceArray.length(); i++) {
JSONObject distanceItems = distanceArray.getJSONObject(i);
final String unit = distanceItems.getString("unit");
final double weight = distanceItems.getDouble("weight");
result.add(new HashMap<String, Double>() {{
put(unit, weight);
}});
}
System.out.println(result.toString()); // output [{km=60.0}, {m=100.0}]
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.