0

I have the following response.

{
  "data": "[{\"{Test}.id\":12984,\"{Test}.url\":\"https://login.test.com/0010b00002CIwX5AAL\"},{\"{Test}.id\":84592,\"{Test}.url\":\"\"}]"
}

I tried to solve it via JSON to Java object deserialization with escaped properties but it looks like I did something wrong or didn't understand properly how to use this approach because I got an empty list in data object.

public class Wrapper {

    @JsonProperty("data")
    @JsonDeserialize(using = ProviderResponseDeserializer.class)
    private List<TestObject> data;
}

public class TestObject{

    @JsonProperty("{Test}.id")
    public Integer id;
    @JsonProperty("{Test}.url")
    public String url;
}

public class ProviderResponseDeserializer extends JsonDeserializer<List<TestObject>> {

    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public List<TestObject> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        return mapper.readValue(jsonParser.getText(), mapper.getTypeFactory().constructCollectionType(List.class, TestObject.class));
    }
}

Could you help me with what I did wrong or suggest some other approach?

Ip Man
  • 77
  • 10

1 Answers1

0

This is same code you have given in the question and it worked correctly.

public class Main {

    public static void main(String[] args) throws IOException {
        String s = "{\"data\":\"[{\\\"{Test}.id\\\":12984,\\\"{Test}.url\\\":\\\"https://login.test.com/0010b00002CIwX5AAL\\\"},{\\\"{Test}.id\\\":84592,\\\"{Test}.url\\\":\\\"\\\"}]\"}";

        ObjectMapper objectMapper = new ObjectMapper();
        Wrapper wrapper = objectMapper.readValue(s, Wrapper.class);

        wrapper.getData().forEach(System.out::println);
    }
}

@Getter
@Setter
class Wrapper {
    @JsonProperty("data")
    @JsonDeserialize(using = ProviderResponseDeserializer.class)
    private List<TestObject> data;
}

@Getter
@Setter
@ToString
class TestObject{
    @JsonProperty("{Test}.id")
    private Integer id;
    @JsonProperty("{Test}.url")
    private String url;
}

class ProviderResponseDeserializer extends JsonDeserializer<List<TestObject>> {
    private static final ObjectMapper mapper = new ObjectMapper();
    @Override
    public List<TestObject> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        return mapper.readValue(jsonParser.getText(), mapper.getTypeFactory().constructCollectionType(List.class, TestObject.class));
    }
}

Output

TestObject(id=12984, url=https://login.test.com/0010b00002CIwX5AAL)
TestObject(id=84592, url=)
ray
  • 1,512
  • 4
  • 11