Используйте библиотеку Джексона
@Test
public void shouldAnswerWithTrue() throws IOException {
String json = "{\"data\":[{\"id\":1,\"name\":\"samsung\",\"memoryId\":32432},{\"id\":2,\"name\":\"apple\",\"memoryId\":34534}]}";
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addDeserializer(Data.class, new DataDeserializer());
objectMapper.registerModule(simpleModule);
Data data = objectMapper.readValue(json, Data.class);
Assert.assertEquals(data.getData().stream().findFirst().get().getMemory().getId(), 32432l);
}
И используйте этот десериализатор данных:
class DataDeserializer extends StdDeserializer<Data> {
public DataDeserializer() {
this(null);
}
public DataDeserializer(Class<?> vc) {
super(vc);
}
@Override
public Data deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
JsonNode node = jp.getCodec().readTree(jp);
Iterator<JsonNode> iterator = node.get("data").iterator();
List<Phone> phones = new ArrayList<>();
System.out.println(node.asText());
while (iterator.hasNext()) {
JsonNode item = iterator.next();
Phone phone = new Phone();
phone.setId(item.get("id").asLong());
phone.setName(item.get("name").asText());
Memory memory = new Memory();
memory.setId(item.get("memoryId").asLong());
phone.setMemory(memory);
phones.add(phone);
}
Data data = new Data();
data.setData(phones);
return data;
}
Pojos:
@Getter
@Setter
@ToString
class Data {
private List<Phone> data;
}
@Getter
@Setter
@ToString
class Phone {
long id;
Memory memory;
String name;
}
@Getter
@Setter
@ToString
class Memory {
long id;
String type;
}