美文网首页
Json字符串格式化功能

Json字符串格式化功能

作者: NewNiu | 来源:发表于2023-02-23 16:10 被阅读0次
    以下是用Java实现将JSON字符串格式化为文本的功能的代码:
    import com.fasterxml.jackson.core.JsonParseException;
    import com.fasterxml.jackson.databind.JsonMappingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.io.IOException;
    
    public class JsonFormatter {
        public static String format(String jsonString) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                Object json = mapper.readValue(jsonString, Object.class);
                return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
            } catch (JsonParseException | JsonMappingException e) {
                e.printStackTrace();
                return jsonString;
            } catch (IOException e) {
                e.printStackTrace();
                return jsonString;
            }
        }
    }
    
    

    这里使用了com.fasterxml.jackson.databind.ObjectMapper库来处理JSON字符串,readValue()方法将JSON字符串转换为Java对象,writerWithDefaultPrettyPrinter()方法将Java对象转换为格式化后的JSON字符串。如果出现异常,方法将返回原始JSON字符串。

    使用ObjectMappter需要引入如下依赖项:
    • implementation 'com.fasterxml.jackson.core:jackson-databind:2.14.2'
    使用时,可以像这样调用format()方法:
    String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
    String formattedJsonString = JsonFormatter.format(jsonString);
    System.out.println(formattedJsonString);
    
    输出结果应该为:
    {
      "name" : "John",
      "age" : 30,
      "city" : "New York"
    }
    

    这是一个格式化后的JSON字符串,易于阅读和理解。

    相关文章

      网友评论

          本文标题:Json字符串格式化功能

          本文链接:https://www.haomeiwen.com/subject/yfrpkdtx.html