简体   繁体   English

如何使用此特定结构创建JSON数组?

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

I intend to create a JSON Array with the following structure. 我打算用以下结构创建一个JSON数组。 The metadata tag is going to constant in all the entries. 元数据标签在所有条目中都将保持不变。 I am stumped. 我感到难过。

[{
        "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;
}

}

Then somewhere else you can just do this: 然后您可以在其他地方执行以下操作:

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);

To read you can just use: 要阅读,您可以使用:

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

Both snippets are taken from my linked wiki article from jackson themselves. 这两个摘录均摘自杰克逊本人的链接维基文章。

Jackson should automatically be able to parse this POJO to an equivalent JSON if configured correctly. 如果配置正确,Jackson应该能够自动将此POJO解析为等效的JSON。 Note: Jackson has to be globally registered and has to know about it. 注意: Jackson必须在全球范围内注册,并且必须了解这一点。 Please read the wiki of what you use to know about it... Jackson in 5 Minutes 请阅读有关您所了解的知识的维基... 5分钟内的杰克逊

Else you could just manually build the JSON like Neeraj said. 否则,您可以像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.

Note: MetaDataCustomClass is just a custom Class having a Value instance variable of type String. 注意: 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