【问题标题】:Serialize, deserialize using jackson使用jackson进行序列化、反序列化
【发布时间】:2021-12-13 23:30:00
【问题描述】:

我正在尝试将我的对象转换为 json,但默认的序列化程序,杰克逊的反序列化程序不起作用。

我怎样才能做到这一点?我知道我可能需要编写一个自定义序列化程序、反序列化程序。我怎样才能做到这一点? 通过添加哪些代码可以工作,是否有一些注释?

这是对象:

@JsonDeserialize(keyUsing = mypairDeserializer.class)
@JsonSerialize(keyUsing = mypairSerializer.class)
HashMap<Set < Mypair > , List < Mypair > > obj;


public class ConditionSerializer extends JsonSerializer<Collection<mypair>> {

    @Override
    public void serialize(final Collection<mypair> conditionSet, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeFieldName("Pair");
        jsonGenerator.writeStartArray();
        for(final Condition condition: conditionSet) {
            jsonGenerator.writeString(mypair.toString());
        }
        jsonGenerator.writeEndArray();
        jsonGenerator.writeEndObject();
    }
}


public class mypairDeserializer extends KeyDeserializer {
    ObjectMapper mapper = new ObjectMapper();
    @Override
    public Collection<mypair> deserializeKey(final String key, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
        // return new mypair(key);
        return mapper.readValue(key, Collection.class);
    }
}

【问题讨论】:

  • 解释为什么它不起作用。有什么例外吗?

标签: java json serialization json-deserialization jackson-databind


【解决方案1】:

上次发帖,大家好,

所以,这是你可以做的一个例子:

请注意,由于我不知道您的对象 Mypair 是什么,因此我使用 User 类做了这个示例:

public class User {
    private int id;
    private String name;

    public User(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    // getters & setters
}

包含您的复杂对象的类:

public class YourClass {

    @JsonSerialize(using = ComplexObjectSerializer.class)
    private Map<Set<User>, List<User>> object;

    public YourClass(Map<Set<User>, List<User>> object) {
        this.object = object;
    }

    public Map<Set<User>, List<User>> getObject() {
        return object;
    }

    public void setObject(Map<Set<User>, List<User>> object) {
        this.object = object;
    }
}

自定义序列化器:

public class ComplexObjectSerializer extends StdSerializer<Map<Set<User>, List<User>>> {

    public ComplexObjectSerializer() {
        this(null);
    }

    public ComplexObjectSerializer(Class<Map<Set<User>, List<User>>> t) {
        super(t);
    }

    private static final long serialVersionUID = 1L;

    @Override
    public void serialize(Map<Set<User>, List<User>> complexObject,
            JsonGenerator jsonGen, SerializerProvider arg2) throws IOException {

        // Suppose you want the following json:
        /**
         * [ { "set":[], "list":[] } ]
         */

        jsonGen.writeStartArray(); // [

        for (Entry<Set<User>, List<User>> entry : complexObject.entrySet()) {
            jsonGen.writeStartObject(); // {
            jsonGen.writeObjectField("set", entry.getKey()); // It will call the default serializer for a Set<User>, ie : [ {"id": 0, "name":"string"} ]

            jsonGen.writeObjectField("list", entry.getValue()); // It will call the default serializer for a List<User>, ie the same thing as the Set above
            jsonGen.writeEndObject(); // }
        }
        jsonGen.writeEndArray(); // ]
    }
}

主要:

        Map<Set<User>, List<User>> complexObject = new HashMap<Set<User>, List<User>>();

        // Add some data in the map ...

        YourClass yourClass = new YourClass(complexObject);

        // Serialize your object
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(yourClass); // It will call your custom serializer
        System.out.println(json);

输出:

{
  "object": [
    {
      "set": [
        {
          "id": 5,
          "name": "userName5"
        },
        {
          "id": 6,
          "name": "userName6"
        }
      ],
      "list": [
        {
          "id": 2,
          "name": "userName2"
        }
      ]
    },
    {
      "set": [
        {
          "id": 4,
          "name": "userName4"
        },
        {
          "id": 3,
          "name": "userName3"
        }
      ],
      "list": [
        {
          "id": 0,
          "name": "userName0"
        },
        {
          "id": 1,
          "name": "userName1"
        }
      ]
    }
  ]
}

【讨论】:

  • 您好,谢谢您的回复。我得到的异常是 InvalidDefinitionException: Cannot find a (Map) Key deserializer for type [collection type;类 java.util.List,包含 [简单类型,类 mypair]]
  • 最终将原始哈希图 obj 分解为两个哈希图,键为 String。
猜你喜欢
  • 1970-01-01
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-10
  • 2015-05-20
  • 1970-01-01
相关资源
最近更新 更多