1 public class JacksonObjectMapperExample { 2 3 public static String formatJson(String jsonStr) throws IOException { 4 ObjectMapper objectMapper = new ObjectMapper(); 5 // 允许没有引号的字段名(非标准) 6 objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); 7 // 允许单引号(非标准) 8 objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); 9 Object json = objectMapper.readValue(jsonStr, Object.class); 10 //美化 11 //System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(json)); 12 //objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); 13 //不美化 14 objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false); 15 16 return objectMapper.writeValueAsString(json); 17 } 18 19 public static void main(String[] args) throws IOException { 20 String test = "{age:29,messages:["msg 1","msg 2","msg 3"],"name":"mkyong"}"; 21 System.out.println(formatJson(test)); 22 } 23 }