簡體   English   中英

如何使用此特定結構創建JSON數組?

[英]How to create a JSON array with this specific structure?

我打算用以下結構創建一個JSON數組。 元數據標簽在所有條目中都將保持不變。 我感到難過。

[{
        "metadata": {
            "Value": "String"
        },
        "name": "String",
        "id": "String"
    },
    {
        "metadata": {
            "Value": "String"
        },
        "name": "String",
        "id": "String"
    }
]
public class yourJsonObject {

private Map<String, String> metadata;

private String name;

private string id;

public yourJsonObject() {

}

public Map<String, String> getMetadata(){
return metadata;
}

public void setMetadata(Map<String, String> metadata){
this.metadata = metadata;
}

public String getName(){
return name;
}

public void setName(String name) {
this.name = name;
}

public String getId(){
return id;
}

public void setId(String id){
this.id = id;
}

}

然后您可以在其他地方執行以下操作:

ObjectMapper mapper = new ObjectMapper(); // create once, reuse
yourJsonObject example = new yourJsonObject(); // have your POJO you want to save
mapper.writeValue(new File("result.json"), example);

要閱讀,您可以使用:

ObjectMapper mapper = new ObjectMapper(); // create once, reuse
yourJsonObject value = mapper.readValue(new File("data.json"), yourJsonObject .class);

這兩個摘錄均摘自傑克遜本人的鏈接維基文章。

如果配置正確,Jackson應該能夠自動將此POJO解析為等效的JSON。 注意: Jackson必須在全球范圍內注冊,並且必須了解這一點。 請閱讀有關您所了解的知識的維基... 5分鍾內的傑克遜

否則,您可以像Neeraj所說的那樣手動構建JSON。

JSONArray array = new JSONArray(); // Create JSONArray Object

JSONObject jsonObject = new JSONObject(); // Your JSONObject which gets added into array
jsonObject.put("metadata",new MetaDataCustomClass("SomeRandomStringValue"));
jsonObject.put("name", "Neeraj");
jsonObject.put("id", "123");

array.add(jsonObject); // Here you push the jsonObject into Array.

注意: MetaDataCustomClass只是一個具有String類型的Value實例變量的自定義類。

Class MetaDataCustomClass {

   private String value;

   public MetaDataCustomClass(String value){
       this.value = value;
   }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM