我很难理解如何将映射值放入数组以及如何迭代该数组。如何使用Jackson JSON将值存储到Java
test.json
[
{
"Name": "Bob",
"Nationality": "",
"City": "Chicago",
"Phone" : "451232424234"
},
......continues with more objects
]
testTemplate.java
//imports
@JSONInclude(Json.Include.Non_NULL)
@JsonPropertyOrder({"Name,"Nationality","City","Phone"})
Public class testTemplate {
@JsonProperty("Name")
private String userName;
@JsonProperty("Nationality")
private String nation;
@JsonProperty("City")
private String city;
@JsonProperty("Phone")
private String phone;
@JsonProperty("Name")
public String getName (String userName) {
this.userName = userName;
}
@JsonProperty("Nationality")
public String nation (String nation) {
this.nation = nation;
}
@JsonProperty("City")
public String city (String city) {
this.city = city;
}
@JsonProperty("Phone")
public String phone (String phone) {
this.phone = phone;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
testParse.java
Public Class testParse {
List<testParse> test;
ObjectMapper mapper;
protected void setUp() throws IOException {
mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT();
test = mapper.readValue(this.getClass().getResourcesAsStream("test.json"),
mapper.getTypeFactory().constructCollectionType(List.class, testParse.class));
我需要帮助澄清第一到底是什么代码做什么,以及如何将JSON属性(名称,国籍,城市,电话)放入Java中。
我的理解是testTemplate文件创建将保存属性的字符串,然后testParse文件具有通过json读取并将所有内容放入“test”(作为数组?)的mapper功能(来自Jackson)。 )
我的目标是在testParse中,如果所有东西都在“测试”中,那么我通读它并开始将它拉出并放入一个folderList中。
public static Map<String, String> userName throws IOException {
Map<String, String> folderList = new TreeMap<>();
//Don't know how, but iterate through "test"
LineIterator it = new LineIterator(//the method used to read the json file);
try {
while(it.hasNext()) {
String line = it.nextLine();
folderList.put(userName,nation) //can I also put city and phone at once as well or should I create another put: folderList.put(userName, city)
return folderList;
这是怎么回事?使用杰克逊映射器后,有没有更好的方法将json的属性放入folderList?
可以请您演示如何将对象添加到testParse.java中的folderList数组中。 – Bobshark
你可以按照这个来获取它http://stackoverflow.com/questions/6349421/how-to-use-jackson-to-deserialise-an-array-of-objects –