【发布时间】:2020-03-23 03:31:43
【问题描述】:
pom.xml
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
</dependency>
</dependencies>
pojo 类:Function.java
public class Function{
private Integer id;
private Set<MenuToFunction> menuToFunctions;
public Integer getId(){
return this.id;
}
public void setId(Integer id){
this.id=id;
}
public Set<MenuToFunction> getMenuToFunctions(){
return this.menuToFunctions;
}
public void setMenuToFunctions(Set<MenuToFunction> menuToFunctions){
this.menuToFunctions=menuToFunctions;
}
}
pojo 类:MenuToFunction.java
public class MenuToFunction{
private Integer id;
public Integer getId(){
return this.id;
}
public void setId(Integer id){
this.id=id;
}
}
我的 json 文件,注意这些 id 是从 1 到 6。
{
"id": 1,
"menuToFunctions": [
{
"id": 1
},
{
"id": 2
},
{
"id": 3
},
{
"id": 4
},
{
"id": 5
},
{
"id": 6
}
]
}
最后,我的测试代码。我使用jackson和gson来反序列化json。
public class ReadJsonFile{
public static void main(String[] args){
try{
String fileAbsolutePath="T:/GetFunctionDetailResponse.json";
Function function=new ObjectMapper().readValue(new File(fileAbsolutePath),Function.class);
for(MenuToFunction menuToFunction:function.getMenuToFunctions()){
System.out.println("menuToFunction.getMenu().getId() with jackson:"+menuToFunction.getId());
}
function=new GsonBuilder().create().fromJson(new FileReader(fileAbsolutePath),Function.class);
for(MenuToFunction menuToFunction:function.getMenuToFunctions()){
System.out.println("menuToFunction.getMenu().getId() with gson:"+menuToFunction.getId());
}
}catch(Exception e){
e.printStackTrace();
}
}
}
控制台输出
menuToFunction.getMenu().getId() with jackson:5
menuToFunction.getMenu().getId() with jackson:3
menuToFunction.getMenu().getId() with jackson:6
menuToFunction.getMenu().getId() with jackson:2
menuToFunction.getMenu().getId() with jackson:4
menuToFunction.getMenu().getId() with jackson:1
menuToFunction.getMenu().getId() with gson:1
menuToFunction.getMenu().getId() with gson:2
menuToFunction.getMenu().getId() with gson:3
menuToFunction.getMenu().getId() with gson:4
menuToFunction.getMenu().getId() with gson:5
menuToFunction.getMenu().getId() with gson:6
那么为什么 Jackson 反序列化 json 不能按顺序打印对象数组,而 gson 可以?
杰克逊有什么配置吗?
我也尝试过最新版本的jackson-2.10.3,但还是有同样的问题。
感谢您的帮助。
【问题讨论】: