使用Jackson JAXRS提供程序序列化DynaBean的LazyDynaList

时间:2016-04-25 12:42:48

标签: java rest java-ee jackson jax-rs

我在JEE应用程序中使用Jackson JAXRS JSON提供程序。

.item-content

我需要发送一个compile group: 'com.fasterxml.jackson.jaxrs', name: 'jackson-jaxrs-json-provider', version: '2.7.3' ,其中每个List<?>都是?个实例。

即:

DynaBean

当我发送此public List<?> findXXX() { DynaClass dynaClass = new BasicDynaClass("Car", null, new DynaProperty[]{ new DynaProperty("wheels", Long.TYPE), new DynaProperty("doors", Long.TYPE)} } ); try { DynaBean car = dynaClass.newInstance(); car.set("wheels", 4); car.set("doors", 2); } // ... List<DynaBean> cars = new LazyDynaList(dynaClass); cars.add(car); return cars; } 时:

List<?>

在构建了响应之后,jackson将此上下文序列化为:

public class SearchEndpoint implements ISearchEndpoint 
{

    @Inject protected SearchService searchService;

    @Override
    public Response search(String lqlSentence)
    {
        return Response.ok().entity(
            this.searchService.findXXX()
        ).build();
    }
}

我只想发送:

[
    {
        "dynaClass":{
            "dynaBeanClass":"org.apache.commons.beanutils.LazyDynaBean",
            "name":"org.apache.commons.beanutils.LazyDynaClass",
            "restricted":false,
            "returnNull":false,
            "dynaProperties":[
                {
                    "name":"wheels",
                    "type":"java.lang.Long",
                    "mapped":false,
                    "indexed":false
                },
                {
                    "name":"doors",
                    "type":"java.lang.Long",
                    "mapped":false,
                    "indexed":false
                }
            ]
        },
        "map":{
            "wheels": 4,
            "doors": 2
        }
    }
]

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

为什么不尝试为DynaClass创建自己的自定义JSON序列化程序?

您的自定义序列化程序看起来像这样。

import java.io.IOException;
import java.util.List;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

public class DynaSerializer extends JsonSerializer<DynaClass> {

    @Override
    public void serialize(DynaClass dyna, JsonGenerator jgen, SerializerProvider provider)
            throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeObject(dyna.getMap());
        jgen.writeEndObject();

    }

}

然后在您的DynaClass中,您将告诉Jackson您正在使用自己的自定义序列化器。

@JsonSerialize(using=DynaSerializer.class)
public class DynaClass{
//Your class definition
}

然后获取您的JSON字符串......

String jsonStr = new ObjectMapper().writeValueAsString(new DynaClass());

对于更多解决方案,请查看此链接,这非常有用。 http://www.baeldung.com/jackson-custom-serialization