java Jackson 中键/值对的序列化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5430524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:05:07  来源:igfitidea点击:

Serialization of key/value pairs in Hymanson?

javarestHymanson

提问by Heiko Rupp

I have a class

我有一堂课

class Foo {
  String key;
  String value;
}

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?

并想将其序列化为"<content of key>":"<content of value>"如何实现这一点(以及如何反序列"myKey":"myVal"化为Foo对象?

I was trying to use

我试图使用

@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.

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

回答by Heiko Rupp

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

我找到了一种方法,它使用这样的 JsonSerializer:

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

The Fooclass needs to know about this:

Foo类需要了解这一点:

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

Deserializing is very similar:

反序列化非常相似:

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

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

这也需要在 Foo 类上进行注释:

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