这是我的JSON字符串:

{"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}]}

我需要将上面的JSON字符串转换为漂亮的打印JSON输出(使用Jackson),如下所示:

{
    "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
        }
    ]
}

谁能根据我上面的例子给我一个例子?如何实现这个场景?我知道有很多例子,但我不能正确地理解它们。任何帮助都将感谢一个简单的例子。

更新:

下面是我正在使用的代码:

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(jsonString));

但这并不适用于我需要输出的方式如上所述。

这是我在上面JSON中使用的POJO:

public class UrlInfo implements Serializable {

    private List<Attributes> attribute;

}

class Attributes {

    private String nm;
    private List<ValueList> lv;
    private String vt;
    private String status;
    private String lmd;

}


class ValueList {
    private String vt;
    private String cn;
    private List<String> v;
}

有人能告诉我,我是否为JSON得到了正确的POJO吗?

更新:

String result = restTemplate.getForObject(url.toString(), String.class);

ObjectMapper mapper = new ObjectMapper();
Object json = mapper.readValue(result, Object.class);

String indented = mapper.defaultPrettyPrintingWriter().writeValueAsString(json);

System.out.println(indented);//This print statement show correct way I need

model.addAttribute("response", (indented));

下面一行输出如下内容:

System.out.println(indented);


{
  "attributes" : [ {
    "nm" : "ACCOUNT",
    "error" : "null SYS00019CancellationException in CoreImpl fetchAttributes\n java.util.concurrent.CancellationException\n\tat java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:231)\n\tat java.util.concurrent.FutureTask.",
    "status" : "ERROR"
  } ]
}

这就是我需要的表现方式。但当我像这样把它添加到模型中:

model.addAttribute("response", (indented));

然后显示在一个结果表单jsp页面,如下所示:

    <fieldset>
        <legend>Response:</legend>
            <strong>${response}</strong><br />

    </fieldset>

我得到的结果是这样的:

{ "attributes" : [ { "nm" : "ACCOUNT", "error" : "null    
SYS00019CancellationException in CoreImpl fetchAttributes\n 
java.util.concurrent.CancellationException\n\tat 
java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:231)\n\tat 
java.util.concurrent.FutureTask.", "status" : "ERROR" } ] }

我不需要。我需要上面打印出来的方式。有人能告诉我为什么会这样吗?


当前回答

如果你格式化字符串并返回像RestApiResponse< string >这样的对象,你会得到不需要的字符,如转义等:\n, \"。解决方案是将您的JSON-string转换为Jackson JsonNode对象并返回RestApiResponse<JsonNode>:

ObjectMapper mapper = new ObjectMapper();
JsonNode tree = objectMapper.readTree(jsonString);
RestApiResponse<JsonNode> response = new RestApiResponse<>();
apiResponse.setData(tree);
return response;

其他回答

你可以通过以下方法来实现:

1. 使用杰克逊

    String formattedData=new ObjectMapper().writerWithDefaultPrettyPrinter()
.writeValueAsString(YOUR_JSON_OBJECT);

导入以下类:

import com.fasterxml.jackson.databind.ObjectMapper;

它的gradle依赖项是:

compile 'com.fasterxml.jackson.core:jackson-core:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3'

2. 使用来自谷歌的Gson

String formattedData=new GsonBuilder().setPrettyPrinting()
    .create().toJson(YOUR_OBJECT);

导入以下类:

import com.google.gson.Gson;

它的gradle是:

compile 'com.google.code.gson:gson:2.8.2'

在这里,您还可以从存储库下载正确的更新版本。

ObjectMapper.readTree()可以在一行中完成:

mapper.readTree(json).toPrettyString();

因为readTree生成了一个JsonNode,所以它应该总是生成等效的漂亮格式的JSON,因为它的JsonNode是底层JSON字符串的直接树表示。

在杰克逊2.10之前

JsonNode.toPrettyString()方法是在Jackson 2.10中添加的。在此之前,需要第二次调用ObjectMapper来编写格式化的结果:

mapper.writerWithDefaultPrettyPrinter()
        .writeValueAsString(mapper.readTree(json));

最简单也是最紧凑的解决方案(适用于v2.3.3):

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValueAsString(obj)

如果你格式化字符串并返回像RestApiResponse< string >这样的对象,你会得到不需要的字符,如转义等:\n, \"。解决方案是将您的JSON-string转换为Jackson JsonNode对象并返回RestApiResponse<JsonNode>:

ObjectMapper mapper = new ObjectMapper();
JsonNode tree = objectMapper.readTree(jsonString);
RestApiResponse<JsonNode> response = new RestApiResponse<>();
apiResponse.setData(tree);
return response;

对于Jackson 1.9,我们可以使用以下代码来实现漂亮的打印。

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);