将字段序列化为json [英] Serializing a field as json

查看:125
本文介绍了将字段序列化为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要向REST服务发送一个JSON主体。不幸的是,服务很老,我需要发送一个包含JSON字符串字段的POJO。所以它看起来像这样:

I need to send a JSON body to REST service. Unfortunately, service is quite old and I need to send a POJO, containing JSON string field. So it looks like this:

class SomeData {
    int id;
    SomePojo jsonField;

    ...
}

所以应该发送SomeData像这样:

So SomeData should be sent like this:

{'id': 1, 'jsonField': some_json_string}

我还没有发现任何杰克逊魔法注释使其有效,我怀疑它可以以某种方式制作,因为Java中的类型擦除并且可能无法为此目的编写自定义序列化程序,但我不确定。

I haven't found any Jackson magic annotation to make it works and I've got a doubt it can be made somehow because of type erasure in Java and it may not be possible to write custom serializer for this purpose but I'm not sure.

您能否建议我如何使其工作或解决方法问题?非常感谢您提前!

Could you please suggest any idea of how I can make it work or workaround the issue? Thank you very much in advance!

推荐答案

当您在Spring环境中使用Jackson时,您可以使用 @JsonSerialize -Annotation

When you are using Jackson in a Spring context, you can make use of the @JsonSerialize-Annotation

假设您有问题中的类,那么您可以在吸气剂上放置上述注释:

Assuming you have the Classes from your question, then you can put the above mentioned annotation on your getter:

public class SomeData {
    int id;
    SomePojo jsonField;

    @JsonSerialize(using = PojoSerializer.class)
    public SomePojo getJsonField(){
         return jsonField;
    }
}

然后创建 PojoSerializer

public class PojoSerializer extends JsonSerializer<SomePojo>{
    @Override
    public void serialize( SomePojo pojo, JsonGenerator jsonGenerator, SerializerProvider serializerProvider ) throws IOException{
        jsonGenerator.writeString(pojo.getSomeString());
    }
}

其余的确适合您

这篇关于将字段序列化为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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