我很难理解如何将映射值放入数组以及如何迭代该数组。
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文件具有映射器功能(来自Jackson),它通过json读取并将所有内容放入“test”(作为数组?)
我的目标是在testParse中,如果所有内容都在“test”中,那么我会仔细阅读,并开始将其拉出并将其放入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;
如何做到这一点?使用jackson映射器后,是否有更好的方法将json的属性放入folderList?
答案 0 :(得分:1)
实际上,testTemplate不生成任何东西,杰克逊在这里所做的只是从“test.json”获取数据为String,然后使用Reflection读取testTemplate.java的格式。基于模板,它只是添加到ObjectMapper对象的+设置,Jackson将test.json转换为对象Java数组。
P / S:你不需要在两个属性中添加注释并获得POJO类的功能,只需要在get函数或属性中执行它,这对Jackson来说已经足够了。