0

there is a json text like this

{"name":"g1","users":"[{\"name\":\"u1\",\"id\":1},{\"name\":\"u2\",\"id\":2}]"}

how to deserialize this text to object? my struct class is like this

static class User {
    private String name;
    private Long id;
}
static class Group {
    private String name;
    private List<User> users;
}

but how to deserialize the text to object

ObjectMapper objectMapper = new ObjectMapper();
Group group = objectMapper.readValue(s, Group.class);
3
  • on first glance it should work, what error You have when running this code ?
    – lukwas
    Commented Dec 8, 2022 at 10:55
  • It seems that your JSON is not good, it should look like {"name":"g1","users":[{"name":"u1","id":1},{"name":"u2","id":2}]} Commented Dec 8, 2022 at 10:56
  • yes the json is not good. the json of the users property is a string .my problem is how to auto deserialize the string to list。
    – xz_
    Commented Dec 9, 2022 at 0:04

1 Answer 1

0

I'm try imp a JsonDeserializer like this.

public class RawJsonDeserializer<T> extends JsonDeserializer<T> implements ContextualDeserializer {
    private final JavaType type;

    public RawJsonDeserializer() {
        this.type = SimpleType.constructUnsafe(Object.class);
    }

    public RawJsonDeserializer(JavaType type) {
        this.type = type;
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
        System.out.println(property.getType());
        return new RawJsonDeserializer<>(property.getType());
    }

    @Override
    public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        return ((ObjectMapper) p.getCodec()).readValue(p.getText(), type);
    }
}

and i apply it on my proterty

 @JsonDeserialize(using = RawJsonDeserializer.class, contentAs = WaybillItem.class) @JsonProperty("responseItems")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.