我使用Spring,Jersey和Jackson来提供生成JSON的API.
我的@Component有一个@Get方法,它返回Response.ok(entity).build().
输出非常紧凑.如何使输出漂亮/格式化?
我想基于一个http参数动态地打印来自Spring MVC Restcontrollers的json响应(如下所示:http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#pretty-print- gzip).
我已经找到了通过静态配置进行漂亮打印的配置,但不是如何动态地进行打印?
使用Spring MVC for REST时,如何让Jackson能够打印出漂亮的JSON?
知道怎么做吗?
我使用json-simple并希望有漂亮的打印用于调试目的.
这是一个非常相关的SO问题:Java中的Pretty-Print JSON
然而,给定线程中的答案不仅修复了缩进,而且还使用键的字符串顺序将项的顺序更改为[a ... z].
有没有办法在不改变JSONObject中项目顺序的情况下修复缩进?
例:
JSONObject myJSon = new JSONObject();
myJSon.put("zzz", 1);
myJSon.put("aaa", 1);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println( gson.toJson(myJSon) );
Run Code Online (Sandbox Code Playgroud)
输出:
{
"aaa": 1,
"zzz": 1
}
Run Code Online (Sandbox Code Playgroud)
期望的输出:
{
"zzz": 1,
"aaa": 1
}
Run Code Online (Sandbox Code Playgroud)
编辑:我正在使用:org.json.simple.JSONObject
我正在使用Jackson 1.9.6(codehaus)在Spring MVC应用程序中对我的响应主体进行JSON序列化,而我却无法找到配置漂亮打印的方法.我能够找到的所有代码示例(比如this和this)都涉及到ObjectMapper或者实例化ObjectWriter,但我目前还没有使用其他任何实例化.我甚至不知道在哪里放这个代码.我所有的Jackson配置都是通过注释序列化为JSON的POJO来处理的.
有没有办法在注释中指定漂亮的打印?我认为他们会把它放在@JsonSerialize中,但它看起来不像.
我要序列化的类看起来像这样:
@JsonAutoDetect
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class JSONObject implements Serializable{...}
Run Code Online (Sandbox Code Playgroud)
我的Spring控制器方法如下所示:
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody List<Object> getMessagesAndUpdates(HttpServletRequest request, HttpServletResponse response) {
JSONObject jsonResponse = new JSONObject();
.
.
.
//this will generate a non-pretty-printed json response. I want it to be pretty-printed.
return jsonResponse;
}
Run Code Online (Sandbox Code Playgroud)