更新
制作这个类
public class Target {
}
制作这个Self.java
import com.google.gson.annotations.SerializedName;
public class Self {
@SerializedName("type")
private String type;
@SerializedName("target")
private Target target;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Target getTarget() {
return target;
}
public void setTarget(Target target) {
this.target = target;
}
}
创建一个Row.java
import com.google.gson.annotations.SerializedName;
public class Row {
@SerializedName("type")
private String type;
@SerializedName("self")
private Self self;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Self getSelf() {
return self;
}
public void setSelf(Self self) {
this.self = self;
}
}
这是Respones.java,将使用 gson 进行序列化
import java.util.ArrayList;
import com.google.gson.annotations.SerializedName;
public class Respones {
@SerializedName("key")
private String key;
@SerializedName("rows")
private ArrayList<Row> rows;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public ArrayList<Row> getRows() {
return rows;
}
public void setRows(ArrayList<Row> rows) {
this.rows = rows;
}
}
以下是检查类是否正常工作的测试代码,
您可以在代码中使用上述模型类,但以下代码严格匹配您的数据,这绝不是生成JSON 数据的标准方式,您要如何填充对象取决于您
import java.util.ArrayList;
import com.google.gson.Gson;
public class TestDrive {
public static void main(String[] args) {
// TODO Auto-generated method stub
Respones respones = new Respones();
respones.setKey("value");
ArrayList<Row> rows = new ArrayList<>();
Row one = new Row();
one.setType("the_type_1");
one.setSelf(new Self());
Row two = new Row();
two.setType("the_type_2");
two.setSelf(new Self());
Row three = new Row();
three.setType("the_type_3");
Self self = new Self();
self.setTarget(new Target());
self.setType("the_type_2");
three.setSelf(self);
rows.add(one);
rows.add(two);
rows.add(three);
respones.setRows(rows);
/**
* This code will convert your ArrayList object to a equivalent JSON
* String
*/
String result = (new Gson()).toJson(respones);
System.out.println(""+result);
/**
* This code will convert your JSON String to a equivalent Response
* Object
*/
Respones respones2 = (new Gson()).fromJson(result, Respones.class);
System.out.println(""+respones2.getKey());
System.out.println(""+respones2.getRows().get(0).getType());
System.out.println(""+respones2.getRows().get(2).getSelf().getType());
}
}
输出
{
"key": "value",
"rows": [
{
"type": "the_type_1",
"self": {
}
},
{
"type": "the_type_2",
"self": {
}
},
{
"type": "the_type_3",
"self": {
"type": "the_type_2",
"target": {
}
}
}
]
}
value
the_type_1
the_type_2