使用Jackson将Java对象序列化为JSON时,抑制包装器对象 [英] Suppress wrapper object when serializing Java object into JSON using Jackson

查看:258
本文介绍了使用Jackson将Java对象序列化为JSON时,抑制包装器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web服务,它将列表作为JSON返回。它使用Jackson将Java POJO列表映射到JSON。问题是JSON表示在数组周围有一个包装器对象,我只想要数组。即,我得到了这个:

I have a web service that returns a list as JSON. It uses Jackson to map a List of Java POJOs into JSON. The problem is that the JSON representation has a wrapper object around the array, and I just want the array. I.e., I'm getting this:

{"optionDtoList":[{...}, ..., {...}]}

当我真正想要的是:

[{...}, ..., {...}]

我正在直接序列化Java List;我没有用包装器对象包装List并序列化包装器对象。杰克逊似乎正在添加JavaScript包装器对象。

I am serializing the Java List directly; I'm not wrapping the List with a wrapper object and serializing a wrapper object. It's Jackson that seems to be adding the JavaScript wrapper object.

我假设我可以在POJO上使用一些注释来抑制包装器对象,但我没有看到它。

I assume there's some annotation I can use on the POJO to suppress the wrapper object but I'm not seeing it.

对解决方案的限制

我想解决这个问题。服务方而不是剥离客户端的包装。客户端是一个jQuery UI小部件(自动完成小部件,不重要),它需要一个简单的数组,我不想修改小部件本身。

I'd like to fix this on the service side rather than peeling off the wrapper on the client. The client is a jQuery UI widget (the autocomplete widget, not that it matters) that expects a simple array and I don't want to modify the widget itself.

我尝试了什么


  • 我尝试用Java POJO数组替换Java POJO列表,结果是一样的。

  • 我试过 @JsonTypeInfo(use = Id.NONE)认为这可能会抑制包装器,但它没有't。

  • I tried replacing the List of Java POJOs with an array of Java POJOs and the result is the same.
  • I tried @JsonTypeInfo(use = Id.NONE) thinking that that might suppress the wrapper, but it didn't.

推荐答案

在我运行的测试模式中:

In a test mode when I run:

org.codehaus.jackson.map.ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
String json = mapper.writeValueAsString( Arrays.asList("one","two","three","four","five") );
System.out.println(json);

返回:

["one","two","three","four","five"]

这是你期望的行为吗?

我可以看到当我通过Spring控制器返回此列表并让MappingJacksonJsonView处理将列表转换为一个json,然后是它周围有一个包装器,它告诉我MappingJacksonJsonView是添加包装器的那个。然后一个解决方案是从控制器显式返回json,例如:

I could see that when I return this list via a Spring controller and let MappingJacksonJsonView handle transforming the list to a json, then yes there is a wrapper around it, which tells me that the MappingJacksonJsonView is the one adding the wrapper. One solution then would be to explicitly return the json from your controller, say:

    @RequestMapping(value = "/listnowrapper")
public @ResponseBody String listNoWrapper() throws Exception{       
    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(Arrays.asList("one","two","three","four","five")); 
}

这篇关于使用Jackson将Java对象序列化为JSON时,抑制包装器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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