com.github.siwenyan.common.QuickJson Maven / Gradle / Ivy
package com.github.siwenyan.common;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class QuickJson {
private static final Logger log = Logger.getLogger(QuickJson.class.getName());
private final static ObjectMapper mapper = new ObjectMapper();
public static String prettyJson(String jsonString) {
try {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonString).getAsJsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gson.toJson(json);
return prettyJson;
} catch (Exception e) {
return jsonString;
}
}
public static String onelineJson(String jsonString) {
try {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonString).getAsJsonObject();
Gson gson = new GsonBuilder().create();
String prettyJson = gson.toJson(json);
return prettyJson;
} catch (Exception e) {
return jsonString;
}
}
public static String prettyJson(Object o) {
try {
String json = mapper.writeValueAsString(o);
return prettyJson(json);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public static String onelineJson(Object o) {
try {
String json = mapper.writeValueAsString(o);
return onelineJson(json);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public static Object readValue(File file, Class> clazz) {
try {
return mapper.readValue(file, clazz);
} catch (Exception e) {
log.warn(e.getMessage());
return null;
}
}
public static String writeValueAsString(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (Exception e) {
log.warn(e.getMessage());
return null;
}
}
private static Object readValue(String s, TypeReference> typeReference) throws IOException {
try {
return mapper.readValue(new ByteArrayInputStream(s.getBytes()), typeReference);
} catch (Exception e) {
try {
s = FileUtils.readFileToString(FileSystemUtils.findFile(s));
return mapper.readValue(new ByteArrayInputStream(s.getBytes()), typeReference);
} catch (Exception e1) {
log.warn(e1.getMessage());
return null;
}
}
}
public static List