将有序JSON字符串构建为对象Java jackson或Gson内部的LinkedHashMap如何? 但是我希望按插入键的顺序来执行此操作。
public class User {
private String user
private String role;
Map<String,String > myLinkedHashMap = new LinkedHashMap<String, String>();
public void setUser(String user) {
this.user = user;
}
public void setRole(String role) {
this.role = role;
}
public String getUser() {
return user;
}
public String getRole() {
return role;
}
...
}
主要
string json= "[ { "user": "Tom", "role": "READER",
"myLinkedHashMap": {
"1": "first",
"2": "second",
"3": "third" } } ]";
output=getUserFromJsonString(json);
public ClaimDoc getUserFromJsonString(String claimDoc) throws
IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(claimDoc, ClaimDoc.class);
}
输出为
[
{
"user": "Tom",
"role": "READER",
"myLinkedHashMap": {
"3": "third"
"1": "first",
"2": "second"
}
}
]
但是我想要插入的顺序,就像这样:
[
{
"user": "Tom",
"role": "READER",
"myLinkedHashMap": {
"1": "first",
"2": "second",
"3": "third"
}
}
]
答案 0 :(得分:0)
在用户类中,而不仅仅是 Map ,请使用 LinkedHashMap ,它将起作用
LinkedHashMap<String,String > myLinkedHashMap = new LinkedHashMap<String, String>();