[英]Convert JSON String to Pretty Print JSON output using Jackson
這是我擁有的 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 String
轉換成 Pretty Print JSON Output(使用 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));
但這不適用於我需要 output 的方式,如上所述。
這是我用於上述 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 時:
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" } ] }
我不需要。 我需要上面打印出來的方式。 誰能告訴我為什么會這樣?
要縮進任何舊的 JSON,只需將其綁定為Object
,例如:
Object json = mapper.readValue(input, Object.class);
然后用縮進寫出來:
String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
這避免了您必須定義實際的 POJO 以將數據映射到。
或者您也可以使用JsonNode
(JSON 樹)。
最簡單也是最緊湊的解決方案(適用於 v2.3.3):
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValueAsString(obj)
使用 Jackson 1.9+ 的新方法如下:
Object json = OBJECT_MAPPER.readValue(diffResponseJson, Object.class);
String indented = OBJECT_MAPPER.writerWithDefaultPrettyPrinter()
.writeValueAsString(json);
輸出將被正確格式化!
對於 Jackson 1.9,我們可以使用以下代碼進行漂亮打印。
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
我認為,這是美化json數據的最簡單的技術,
String indented = (new JSONObject(Response)).toString(4);
其中Response是一個字符串。
只需在toString()
方法中傳遞 4(indentSpaces) toString()
。
注意:它在沒有任何庫的 android 中運行良好。 但是在 java 中你必須使用org.json庫。
ObjectMapper.readTree()
可以在一行中完成:
mapper.readTree(json).toPrettyString();
由於readTree
生成一個JsonNode
,這應該幾乎總是生成等效的漂亮格式的 JSON,因為它JsonNode
是底層 JSON 字符串的直接樹表示。
JsonNode.toPrettyString()
方法是在 Jackson 2.10 中添加的。 在此之前,需要對ObjectMapper
進行第二次調用來編寫漂亮的格式化結果:
mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(mapper.readTree(json));
這看起來可能是您問題的答案。 它說它正在使用 Spring,但我認為在你的情況下它仍然可以幫助你。 讓我在這里內聯代碼,這樣更方便:
import java.io.FileReader;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
public class Foo
{
public static void main(String[] args) throws Exception
{
ObjectMapper mapper = new ObjectMapper();
MyClass myObject = mapper.readValue(new FileReader("input.json"), MyClass.class);
// this is Jackson 1.x API only:
ObjectWriter writer = mapper.defaultPrettyPrintingWriter();
// ***IMPORTANT!!!*** for Jackson 2.x use the line below instead of the one above:
// ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
System.out.println(writer.writeValueAsString(myObject));
}
}
class MyClass
{
String one;
String[] two;
MyOtherClass three;
public String getOne() {return one;}
void setOne(String one) {this.one = one;}
public String[] getTwo() {return two;}
void setTwo(String[] two) {this.two = two;}
public MyOtherClass getThree() {return three;}
void setThree(MyOtherClass three) {this.three = three;}
}
class MyOtherClass
{
String four;
String[] five;
public String getFour() {return four;}
void setFour(String four) {this.four = four;}
public String[] getFive() {return five;}
void setFive(String[] five) {this.five = five;}
}
您可以使用以下方式實現此目的:
1. 使用 Apache 中的 Jackson
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;
它的等級是:
compile 'com.google.code.gson:gson:2.8.2'
在這里,您還可以從存儲庫下載正確的更新版本。
由於jackson-databind:2.10
JsonNode 有toPrettyString()
方法可以輕松格式化 JSON:
objectMapper
.readTree("{}")
.toPrettyString()
;
從文檔:
public String toPrettyString()
替代
toString()
將使用 Jackson 默認漂亮打印機序列化此節點。自從:
2.10
如果您格式化字符串並返回像RestApiResponse<String>
對象,您將獲得不需要的字符,如轉義等: \\n
, \\"
。解決方案是將您的 JSON 字符串轉換為 Jackson JsonNode 對象並返回RestApiResponse<JsonNode>
:
ObjectMapper mapper = new ObjectMapper();
JsonNode tree = objectMapper.readTree(jsonString);
RestApiResponse<JsonNode> response = new RestApiResponse<>();
apiResponse.setData(tree);
return response;
任何使用 POJO、DDO 或響應 class 返回其 JSON 的人都可以在其屬性文件中使用spring.jackson.serialization.indent-output=true 。 它會自動格式化響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.