杰克逊中键/值对的序列化? [英] Serialization of key/value pairs in Jackson?

查看:98
本文介绍了杰克逊中键/值对的序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级

class Foo {
  String key;
  String value;
}

并希望将其序列化为< content of key>:< value of content>
我如何实现这一目标(以及如何反序列化myKey:myVal进入 Foo 对象?

and want to serialize this into "<content of key>":"<content of value>" How can I achieve this (and how to deserialize "myKey":"myVal" into a Fooobject?

我试图使用

@JsonValue
public String toString() {
   return "\"" + key + "\":\"" + value + "\"";
}

但显然最终会有太多引号。

But clearly end up with too many quotes.

@JsonValue
public String toString() {
    return key + ":" + value;
}

也不起作用,因为它没有创建足够的报价。

also does not work, as it does not create enough quotes.

推荐答案

我找到了一种方法,就是这样使用JsonSerializer:

I found one way, which is using a JsonSerializer like this:

public class PropertyValueSerializer extends JsonSerializer<Foo> {

    @Override
    public void serialize(Foo property_value, JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider) throws IOException, JsonProcessingException {

        jsonGenerator.writeStartObject();
        jsonGenerator.writeFieldName(property_value.getKey());
        jsonGenerator.writeString(property_value.getValue());
        jsonGenerator.writeEndObject();
    }

Foo 类需要了解这一点:

@JsonSerialize(using = PropertyValueSerializer.class)
public class Foo {

反序列化非常相似:

public class PropertyValueDeserializer extends JsonDeserializer<PROPERTY_VALUE> {    

    @Override
    public Foo deserialize(JsonParser jsonParser,
                                      DeserializationContext deserializationContext) throws IOException, JsonProcessingException {

        String tmp = jsonParser.getText(); // {
        jsonParser.nextToken();
        String key = jsonParser.getText();
        jsonParser.nextToken();
        String value = jsonParser.getText();
        jsonParser.nextToken();
        tmp = jsonParser.getText(); // }

        Foo pv = new Foo(key,value);
        return pv;
    }

这也需要在Foo类上注释:

And this also needs to be annotated on the Foo class:

@JsonSerialize(using = PropertyValueSerializer.class)
@JsonDeserialize(using = PropertyValueDeserializer.class)
public class Foo implements Serializable{

这篇关于杰克逊中键/值对的序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆