java jackson json format/compact output

方法很简单,如果有对应的格式化类就给他传格式化类,如果没有可以直接调用。

主要是

writerWithDefaultPrettyPrinter

这个方法,如果想做一个自定义的输出类,则要实现一个PrettyPrinter这个接口,反正先凑合用了。

用maven的童鞋们可以用下面的dependency加入jackson包,如果不是的话就上网找吧,一大堆。
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-lgpl</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>1.9.2</version>
</dependency>

/*
 * @(#)JsonUtil.java $version 2013-10-22
 *
 * Copyright 2013- kimnote.com. All rights Reserved.
 * @Email:a4l8888@gmail.com
 * @site:http://www.kimnote.com
 */

package com.kimnote;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * @author jongsuny
 */
public class JsonUtil {
	private static Logger log = Logger.getLogger(JsonUtil.class);
	/**
	 * return pretty formatted json string
	 * @param json
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String prettyPrinter(String json,Class clazz) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			Object jsons = mapper.readValue(json, clazz);
			return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsons);
		}catch (Exception e) {
			log.error(e.getLocalizedMessage());
			log.error("prettyPrinter:"+json);
		}
		return json;
	}
	public static String prettyPrinter(String json) {
		return prettyPrinter(json,Object.class);
	}
	/**
	 * return compact formatted json string
	 * @param json
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String compactPrinter(String json,Class clazz) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			Object jsons = mapper.readValue(json, clazz);
			return mapper.writeValueAsString(jsons);
		}catch (Exception e) {
			log.error(e.getLocalizedMessage());
			log.error("prettyPrinter:"+json);
		}
		return json;
	}
	public static String compactPrinter(String json) {
		return compactPrinter(json,Object.class);
	}

	public static void main(String[] args) {
		String text = "{\"attributes\":[{\"nm\":\"ACCOUNT\",\"lv\":[{\"v\":{\"Id\":null,\"State\":null},\"vt\":\"java.util.Map\",\"cn\":1}],\"vt\":\"java.util.Map\",\"status\":\"SUCCESS\",\"lmd\":13585},{\"nm\":\"PROFILE\",\"lv\":[{\"v\":{\"Party\":null,\"Ads\":null},\"vt\":\"java.util.Map\",\"cn\":2}],\"vt\":\"java.util.Map\",\"status\":\"SUCCESS\",\"lmd\":41962}]}";
		String res = prettyPrinter(text);
		System.out.println("prettyPrint:");
		System.out.println(res);
		String compact = compactPrinter(res);
		System.out.println("compactPrint:");
		System.out.println(compact);
	}
}

 

java json 格式化输出,java json 紧凑输出

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>