将JSON字段序列化为JSON

时间:2013-12-11 18:36:30

标签: java json serialization jackson

如果它包含JSON对象,我正在尝试将String字段序列化为JSON。为此,我写了一个自定义序列化器:

public class TryJsonStringSerializer extends JsonSerializer<String> {
    @Override
    public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) 
            throws IOException, JsonProcessingException {
        if (value == null) {
            return;
        }
        value = value.trim();
        if (value.startsWith("{") && value.endsWith("}")) {
            jsonGenerator.writeRaw(value);
        } else {
            jsonGenerator.writeString(value);
        }
    }

}

但是我收到以下错误:

org.codehaus.jackson.JsonGenerationException: Can not write a field name, expecting a value
org.codehaus.jackson.impl.JsonGeneratorBase._reportError(JsonGeneratorBase.java:480)
org.codehaus.jackson.impl.Utf8Generator.writeFieldName(Utf8Generator.java:292)
org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:422)
org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:446)
org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
org.codehaus.jackson.map.ser.std.StdContainerSerializers$IndexedListSerializer.serializeContents(StdContainerSerializers.java:122)
org.codehaus.jackson.map.ser.std.StdContainerSerializers$IndexedListSerializer.serializeContents(StdContainerSerializers.java:71)
org.codehaus.jackson.map.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:86)
org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:610)
org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:1613)
...

实现这一目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:6)

public class TryJsonStringSerializer extends JsonSerializer<String> {

    private RawSerializer<String> rawSerializer = new RawSerializer<String>(String.class);
    private ToStringSerializer stringSerializer = ToStringSerializer.instance;

    @Override
    public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) 
            throws IOException, JsonProcessingException {
        if (value == null) {
            return;
        }
        value = value.trim();
        if (value.startsWith("{") && value.endsWith("}")) {
            rawSerializer.serialize(value, jsonGenerator, serializerProvider);
        } else {
            stringSerializer.serialize(value, jsonGenerator, serializerProvider);
        }
    }

}

答案 1 :(得分:1)

您可能想要使用特殊注释:@JsonRawValue,请参阅docs