简体   繁体   English

Spring使用JSONObject字段反序列化对象

[英]Spring deserialize object with JSONObject field

I'm having problems to de-serialize an object containing a JSON field in spring. 我在春季遇到反序列化包含JSON字段的对象的问题。 I have a DataTable data structure that has both String fields and a field that should contain a JSONObject: 我有一个DataTable数据结构,该结构同时具有String字段和应包含JSONObject的字段:

public class DataTable {

        private String identifier;  
        private String version;         
        private JSONObject content;

        //getters and setters 
}

I want to be able to persist this object and retrieve it later on. 我希望能够保留该对象并在以后检索它。 When I post such a DataTable object to my Controller and try to retrieve it later, my content field will be empty, regardless of the contents I posted: 当我将这样的DataTable对象发布到Controller并稍后尝试检索它时,无论发布的内容如何,​​我的content字段都将为空:

{
  "identifier": "id1",
  "version": "0.0.1",
  "content": {
    "empty": true
  }
}

It seems that jackson is not able to correctly de-serialize the JSONObject type field and will just leave it empty instead. 杰克逊似乎无法正确反序列化JSONObject type字段,而是将其保留为空。 How can I make it deserialize the field correctly? 如何使其正确反序列化该字段?

Jackson has the jackson-datatype-json-org module, which allows us to combine json.org objects with POJOs or deserialize to json.org objects as the top level object. Jackson具有jackson-datatype-json-org模块,该模块使我们可以将json.org对象与POJO组合在一起或反序列化为json.org对象,作为顶级对象。

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-json-org</artifactId>
  <version>${jackson2.version}</version>
</dependency>

Here is a test (don't forget to register the JsonOrgModule ). 这是一个测试(不要忘记注册JsonOrgModule )。

public class JsonOrgJacksonTest {

    private final String json =
            "{" +
            "  \"id\": \"one\"," +
            "  \"content\": {" +
            "    \"foo\": \"bar\"," +
            "    \"baz\": \"blah\"" +
            "  }" +
            "}";

    @Test
    public void testJsonOrg() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JsonOrgModule());

        Model model = mapper.readValue(json, Model.class);

        assertThat(model.getId()).isEqualTo("one");
        assertThat(model.getContent().get("foo")).isEqualTo("bar");
        assertThat(model.getContent().get("baz")).isEqualTo("blah");
    }

    public static class Model {
        private String id;
        private JSONObject content;

        public String getId() { return id; }
        public void setId(String id) { this.id = id; }

        public JSONObject getContent() { return content; }
        public void setContent(JSONObject content) { this.content = content; }
    }
}

JSONObject is not supposed to be serialized. JSONObject不应该序列化。 It is for an internal use. 它仅供内部使用。 If you want to have a JSON representation of this data structure without a model (dedidated class) try converting it into a Map. 如果您想在没有模型(专用类)的情况下使用此数据结构的JSON表示,请尝试将其转换为Map。

Map<String,Object> result =
    new ObjectMapper().readValue(dataTable.getContent(), HashMap.class);

You can use a custom deserializer for this: 您可以为此使用自定义解串器:

public class Test {
  public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule("configModule",   Version.unknownVersion());
    module.addDeserializer(DataTable.class, new DeSerializer());
    mapper.registerModule(module);
    // DataTable readValue = mapper.readValue(<xml source>);
  }
}

class DeSerializer extends StdDeserializer<DataTable> {

  protected DeSerializer() {
    super(DataTable.class);
  }

  @Override
  public DataTable deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    // use p.getText() and p.nextToken to navigate through the xml and construct DataTable object
    return new DataTable();

  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM