所需依赖包
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
JSon转换格式化工具类实现
import java.io.IOException;
import java.io.InputStream;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtil {
private static ObjectMapper mapper = new ObjectMapper();
public static String string2Json(String src) throws IOException {
return mapper.writeValueAsString(src);
}
public static <T> T string2Object(String str, Class<T> clazz) throws IOException {
return mapper.readValue(str, clazz);
}
public static <T> T inputstream2Object(InputStream src, Class<T> clazz) throws IOException {
return mapper.readValue(src, clazz);
}
public static String format(String jsonStr) {
int level = 0;
StringBuffer jsonFormatStr = new StringBuffer();
for (int i = 0; i < jsonStr.length(); i++) {
char c = jsonStr.charAt(i);
if (level > 0 && '\n' == jsonFormatStr.charAt(jsonFormatStr.length() - 1)) {
jsonFormatStr.append(getLevelStr(level));
}
switch (c) {
case '{':
case '[':
jsonFormatStr.append(c + "\n");
level++;
break;
case ',':
jsonFormatStr.append(c + "\n");
break;
case '}':
case ']':
jsonFormatStr.append("\n");
level--;
jsonFormatStr.append(getLevelStr(level));
jsonFormatStr.append(c);
break;
default:
jsonFormatStr.append(c);
break;
}
}
return jsonFormatStr.toString();
}
public static String object2String(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private static String getLevelStr(int level) {
StringBuffer levelStr = new StringBuffer();
for (int i = 0; i < level; i++) {
levelStr.append("\t");
}
return levelStr.toString();
}
}