spring 如何使用Jackson将字符串值反序列化为List

h6my8fg2  于 2022-12-17  发布在  Spring
关注(0)|答案(1)|浏览(183)

有一个像这样的json文本

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

如何将文本反序列化为对象?我结构类是这样的

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

而是如何将文本反序列化为对象

ObjectMapper objectMapper = new ObjectMapper();
Group group = objectMapper.readValue(s, Group.class);
qlzsbp2j

qlzsbp2j1#

我尝试像这样imp一个JSON反序列化器。

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);
    }
}

我把它用在我的财产上

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

相关问题