Jackson 美化输出JSON,优雅的输出JSON数据,格式化输出JSON数据... ...

soゝso 2017-09-05 14:03:51 11161

一下用了这么多形容词,就是怕你们找不到。Jackson 美化输出JSON,优雅的输出JSON数据,格式化输出JSON数据

其实本站的第一个工具,也就是首页的,就是JSON格式化输出,但是增加了校验功能,以及中文提示问题所在。比如如下  JSON  少了一个“,”。

好了,介绍完毕,开始走代码吧。

Jackson 格式化输出JSON 代码说明(对象)

我们一般输出就是普通的toString 输出。如下代码:

Demo demo = new Demo("sojson",4,"http://www.sojson.com");
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(demo));

输出结果:

{"name":"sojson","age":4,"domain":"http://www.sojson.com"}

非常不利于肉眼观看,而且一大坨,如果是JSON很大的话,那么更难受。那么我们美化输出呢?

美化/优雅/格式化输出,代码如下:

public static void main(String[] args) throws JsonProcessingException {
    Demo demo = new Demo("sojson",4,"http://www.sojson.com");
    ObjectMapper mapper = new ObjectMapper();
    //普通输出
    System.out.println(mapper.writeValueAsString(demo));
    //格式化/美化/优雅的输出
    System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(demo));
}

输出结果:

{
  "name" : "sojson",
  "age" : 4,
  "domain" : "http://www.sojson.com"
}

是不是结果很nice?下面再看下字符串输出。

Jackson 格式化输出JSON 代码说明(字符)

其实这里就是把字符串转成对象(Object ),然后再输出的。

优雅输出 Java代码:

public static void main(String[] args) throws IOException {
   //已知一个json 字符串
    String json = "{\"name\":\"sojson\",\"age\":4,\"domain\":\"http://www.sojson.com\"}";
    //求优雅输出
    ObjectMapper mapper = new ObjectMapper();
    Object obj = mapper.readValue(json, Object.class);
    System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj));
}

输出结果:

{
  "name" : "sojson",
  "age" : 4,
  "domain" : "http://www.sojson.com"
}

这里有的同学是不是想到,如果直接用上面的方法(writerWithDefaultPrettyPrinter() )呢,因为参数类型是Object ,其实我看了源码,Object 是为了你方便传参为各种你的对象。如果你传的String ,那么直接出来String 了。也就是还是输出原来的方式。当然你也可以试试。

Jackson Maven引入:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.7.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.7.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.7.4</version>
</dependency>

测试类请在附件中下载。

版权所属:SO JSON在线解析

原文地址:https://www.sojson.com/blog/245.html

转载时必须以链接形式注明原始出处及本声明。


附件下载:

备注:点击文件名下载,附件源来自云端,只能在本站下载。复制下载链接无效。

本文主题:

如果本文对你有帮助,那么请你赞助我,让我更有激情的写下去,帮助更多的人。

相关文章
Jackson 美化输出JSON优雅输出JSON数据格式化输出JSON数据... ...
Jackson 转换JSON,SpringMVC ajax 输出,当值为null或者空不输出字段@JsonInclude
JSON数据格式JSON格式化介绍,JSON格式介绍。
JSOUP 教程,JSOUP请求JSON ,JSOUP返回JSON 数据
液厂JSON数据-来自云端数据
JSON格式讲解,JSON获取对象,JSONObject和JSONArray的操作
为什么很多第三方接口,都改成了基于http,直接传递json数据的方式来代替webservice?
Java tojson,Java中json-lib的各种数据转换,及对象转换
Jackson 时间格式化,时间注解 @JsonFormat 用法、时差问题说明
cpu资源采集.json
最新文章
液厂JSON数据-来自云端数据 FreeMarker template error (DEBUG mode; use RETHROW in production!): The following has evaluated to null or missing: ==> it.readCount [in template "www/jsonText/x_left.ftl" at line 113, column 145] ---- Tip: It's the step after the last dot that caused this error, not those before it. ---- Tip: If the failing expression is known to be legally refer to something that's sometimes null or missing, either specify a default value like myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)?? ---- ---- FTL stack trace ("~" means nesting-related): - Failed at: ${it.readCount?string(0)} [in template "www/jsonText/x_left.ftl" in macro "left" at line 113, column 143] - Reached through: @api target="docleftInfoTag" userId="... [in template "www/jsonText/x_left.ftl" in macro "left" at line 4, column 1] - Reached through: @n_left.left "${entity.userId?default... [in template "www/jsonText/x_details_4.ftl" at line 103, column 9] ---- Java stack trace (for programmers): ---- freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...] at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:131) at freemarker.core.UnexpectedTypeException.newDesciptionBuilder(UnexpectedTypeException.java:77) at freemarker.core.UnexpectedTypeException.(UnexpectedTypeException.java:40) at freemarker.core.BuiltInsForMultipleTypes$stringBI._eval(BuiltInsForMultipleTypes.java:617) at freemarker.core.Expression.eval(Expression.java:78) at freemarker.core.MethodCall._eval(MethodCall.java:55) at freemarker.core.Expression.eval(Expression.java:78) at freemarker.core.Expression.evalAndCoerceToString(Expression.java:82) at freemarker.core.DollarVariable.accept(DollarVariable.java:41) at freemarker.core.Environment.visit(Environment.java:324) at freemarker.core.MixedContent.accept(MixedContent.java:54) at freemarker.core.Environment.visitByHiddingParent(Environment.java:345) at freemarker.core.IteratorBlock$IterationContext.executeNestedBlockInner(IteratorBlock.java:268) at freemarker.core.IteratorBlock$IterationContext.executeNestedBlock(IteratorBlock.java:220) at freemarker.core.IteratorBlock$IterationContext.accept(IteratorBlock.java:194) at freemarker.core.Environment.visitIteratorBlock(Environment.java:572) at freemarker.core.IteratorBlock.acceptWithResult(IteratorBlock.java:78) at freemarker.core.IteratorBlock.accept(IteratorBlock.java:64) at freemarker.core.Environment.visit(Environment.java:324) at freemarker.core.MixedContent.accept(MixedContent.java:54) at freemarker.core.Environment.visitByHiddingParent(Environment.java:345) at freemarker.core.ConditionalBlock.accept(ConditionalBlock.java:48) at freemarker.core.Environment.visit(Environment.java:324) at freemarker.core.MixedContent.accept(MixedContent.java:54) at freemarker.core.Environment.visit(Environment.java:324) at freemarker.core.Environment$NestedElementTemplateDirectiveBody.render(Environment.java:2255) at com.sojson.core.tags.WYFTemplateModel.execute(WYFTemplateModel.java:48) at freemarker.core.Environment.visit(Environment.java:389) at freemarker.core.UnifiedCall.accept(UnifiedCall.java:104) at freemarker.core.Environment.visitByHiddingParent(Environment.java:345) at freemarker.core.Environment.visitAndTransform(Environment.java:425) at freemarker.core.UnifiedCall.accept(UnifiedCall.java:107) at freemarker.core.Environment.visit(Environment.java:324) at freemarker.core.Macro$Context.runMacro(Macro.java:184) at freemarker.core.Environment.invoke(Environment.java:701) at freemarker.core.UnifiedCall.accept(UnifiedCall.java:84) at freemarker.core.Environment.visit(Environment.java:324) at freemarker.core.MixedContent.accept(MixedContent.java:54) at freemarker.core.Environment.visit(Environment.java:324) at freemarker.core.Environment.process(Environment.java:302) at freemarker.template.Template.process(Template.java:325) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.processTemplate(FreeMarkerView.java:367) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.doRender(FreeMarkerView.java:284) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.renderMergedTemplateModel(FreeMarkerView.java:234) at org.springframework.web.servlet.view.AbstractTemplateView.renderMergedOutputModel(AbstractTemplateView.java:167) at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1286) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1041) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:984) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176) at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145) at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92) at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:224) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487) at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339) at org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:213) at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:171) at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145) at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92) at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:224) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:61) at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108) at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137) at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125) at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66) at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449) at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365) at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90) at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83) at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383) at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362) at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745)