Java中输出JSON格式化

使用阿里的FastJson

  • pom.xml中的依赖

<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>fastjson</artifactId>
     <version>1.2.62</version>
</dependency>
  • java中的代码

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
//工具类
public class CommonUtils {
      //json美化的方法
		public static String prettyJson(String reqJson){
              JSONObject object = JSONObject.parseObject(reqJson);
              String prettyJson = JSON.toJSONString(object, SerializerFeature.PrettyFormat, 				   SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat);
             return prettyJson;
    }
}
  • 测试类

public  class Test{
		public static void main(String arg[]) {
		String jsonstr = "{" +
				            "\"Name\":\"fanny\"," +
				            "\"age\":\"1000\"," +
				             "\"location\":\"beijing\"," +
				            "}";
		CommonUtils .prettyJson(jsonstr );
		}
}
  • 测试结果

{
	"location":"beijing",
	"age":"1000",
	"Name":"fanny"
}
发布了81 篇原创文章 · 获赞 10 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/fhf2424045058/article/details/105299233