gpt4 book ai didi

java - 在用户对象 Java Jackson 或 Gson 的一侧将有序的 JSON 字符串构建到 LinkedHashMap 如何?

转载 作者:搜寻专家 更新时间:2023-11-01 03:45:56 24 4
gpt4 key购买 nike

在对象 Java jackson 或 Gson 中将有序的 JSON 字符串构建到 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"
}
}
]

最佳答案

在 User 类而不只是 Map 使用 LinkedHashMap 它会起作用

LinkedHashMap<String,String > myLinkedHashMap =  new LinkedHashMap<String, String>();

关于java - 在用户对象 Java Jackson 或 Gson 的一侧将有序的 JSON 字符串构建到 LinkedHashMap 如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55089471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com