Reputation: 93
I have a JSON
payload of the format, with each value a list with single map element:
{
"redundant_str_1": [
{
"attr_1": "val1",
"attr_2": "val2"
}
],
"rendundant_str_2": [
{
"attr_1": "val4",
"attr_2": "val3"
}
]
}
Model is:
public class MyObj {
private String attr_1;
private String attr_2;
}
How can I map above response to List<MyObj>
by neglecting the keys and taking only element from lists?
Upvotes: 1
Views: 98
Reputation: 38655
Your response is of form Map<String, List<MyObj>>
. You can deserialise it to given type and after this convert to a List<MyObj>
.
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import lombok.Data;
import lombok.ToString;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class MyObjApp {
public static void main(String[] args) throws IOException {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = JsonMapper.builder().build();
TypeReference<Map<String, List<MyObj>>> respType = new TypeReference<Map<String, List<MyObj>>>() {};
Map<String, List<MyObj>> response = mapper.readValue(jsonFile, respType);
List<MyObj> myObjs = response.values().stream().flatMap(Collection::stream).collect(Collectors.toList());
System.out.println(myObjs);
}
}
@Data
@ToString
class MyObj {
private String attr_1;
private String attr_2;
}
Above code prints:
[MyObj(attr_1=val1, attr_2=val2), MyObj(attr_1=val4, attr_2=val3)]
Upvotes: 0
Reputation: 178
You can use Jackson
(add dependencies to jackson-core
and jackson-databind
):
String json = "[" +
"{\"attr_1\": \"val1\", \"attr_2\": \"val2\"}, " +
"{\"attr_1\": \"val4\", \"attr_2\": \"val3\"}"
+ "]";
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
List<MyObj> list = Arrays.asList(mapper.readValue(json, MyObj[].class));
Or, if you add to MyObj
setters on fields or make them public there will be no needed the row:
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
Upvotes: 0
Reputation: 704
String json = "{\"redundant_str_1\": [{\"attr_1\": \"val1\", \"attr_2\": \"val2\"}], \"rendundant_str_2\": [{\"attr_1\": \"val4\", \"attr_2\": \"val3\"}]}";
ObjectMapper objectMapper = new ObjectMapper();
List<MyObj> myObjList = new ArrayList<>();
ObjectNode objectNode = (ObjectNode) objectMapper.readTree(json);
for (Iterator<JsonNode> it = objectNode.elements(); it.hasNext(); ) {
ArrayNode arrayNode = (ArrayNode) it.next();
MyObj myObj = objectMapper.treeToValue(arrayNode.get(0),MyObj.class);
myObjList.add(myObj);
}
System.out.println("List : " + myObjList);
Output :
List : [MyObj{attr_1='val1', attr_2='val2'}, MyObj{attr_1='val4',attr_2='val3'}]
Upvotes: 1