我正在使用 resteasy 开发一个宁静的网络服务。早些时候,提供者是杰克逊。
结果输出是
[
{
"status": {
"id": 22,
"name": "VERIFY",
"note": ""
}
},
{
"status": {
"id": 23,
"name": "ACCEPTED",
"note": ""
}
},
{
"status": {
"id": 24,
"name": "POSTPONED",
"note": "for cancel update"
}
},
{
"status": {
"id": 29,
"name": "AMC(NEW)"
}
},
{
"status": {
"id": 30,
"name": "AMC(ASSIGNED)"
}
}
]
后来,我们搬到了 gson 作为提供者。http://eclipsesource.com/blogs/2012/11/02/integrating-gson-into-a-jax-rs-based-application/
输出变化为:
[
{
"id": 0,
"name": "DISABLE"
},
{
"id": 1,
"name": "ENABLE"
},
{
"id": 31,
"name": "REJECTED",
"note": ""
},
{
"id": 25,
"name": "ASSIGNED"
}
]
类定义
package com.apt.common.web.pojo;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Status {
Integer id;
String name;
private String note;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
return name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Status other = (Status) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
输出完全不同。
使用杰克逊
{
"status": {
"id": 22,
"name": "VERIFY",
"note": ""
}
}
使用 gson
{
"id": 0,
"name": "DISABLE"
}
使用 gson 生成 json 的代码是
Gson gson=new Gson();
Type fooType = new TypeToken<List<Status>>() {}.getType();
return gson.toJson(statuses,fooType);
如何使用 gson 实现相同的输出?