不固定的Json返回字段
JasonDev324

特殊的Json实体,Content返回的值是变化的。

1
2
3
4
5
{
"status",200
"type",1
"content","不定值内容"
}
参数名 说明 类型
Status 200 int
Content “各种类型” String
Type 11 int

content可以返回下列不同的值。

  • 当type为1 时,返回结果如下:
参数名 类型 说明
title String 标题
content String 内容

即代码如下

1
2
3
4
5
6
7
8
{
"type": 2,
"content": {
"content": "收数",
"title": "收数"
},
"status": 200
}
  • 当type为2时,返回结果如下:
参数名 类型 说明
teacher String 名称
datetime long 请假时间
content String 请假原因
1
2
3
4
5
6
7
8
9
{
"type": 16,
"content": {
"content": "春节放假",
"teacher": "系统管理员",
"datetime": 1456815436000
},
"status": 200
}
  • 当type为3时,返回结果如下:(该content为一个数组列表,以下为数组成员)
参数名 类型 说明
student String 学生名称
paytime long 支付时间
money float 交费金额
refundmoney float 退费金额
invoicemoney float 发票金额
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"type": 13,
"content": [
{
"student": "测试交费888",
"money": 500,
"paytime": 1453620358000,
"invoicemoney": 500,
"refundmoney": 0,
"invoicetitle": "2016年1月28日10:58:38",
"invoicetime": 1453910400000
}
],
"status": 200
}

根据代码,我们可以设计Json实体如下所示

1
2
3
4
5
6
7
public class JsonTest {

private int type;
private int status;
private Object content;
// ...get、set方法....
}

按照上述Type为1、2的时候,可以创建一个JsonTest内部类如下

1
2
3
4
5
6
7
8
9
10
11
public class JsonTest {
.
.
.
public static class MsgInfo{
private String content;
private String title;
private String teacher;
private long datetime;
}
}

因为content字段是变化的,我们需要根据实际情况(上述字段type)来判断返回的值是那种类型。因此我们需要对getContent()做处理。

默认情况,当你声明content为Object类型的时候,其返回值是LinkedHashMap类型的。然而这种类型是不能转为MsgInfo的,所以我们要重新组装json字符串。更多情况如下表(Json与Java实体对照表)。

重写getContent()方法的思路

  1. 创建相关的JsonObject对象、JsonArray对象
  2. 根据type的值,从而对JsonObject或者JsonArray处理。
  3. 利用Set集合、JsonObject的addProperty方法、toString方法进行拼装。
  4. 最后返回拼装json字符串。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
if(type ==1 || type == 2){
//1.将字段名保存在Set集合中
//2.调用addProperty方法为对象添加属性。
for (String key : set) {
jsonObject.addProperty(key, String.valueOf(((LinkedTreeMap) content).get(key)));
}
result = "{\"infos\":" + jsonObject.toString() + "}";
//1.拼Json字符串,定义一个返回的字段名infos
//2.添加相应的括号、冒号
//3.在JsonTest实体类中创建一个MsgInfo对象 名为infos即可
}else{
Iterator iterator = ((ArrayList) content).iterator();
while (iterator.hasNext()) {
LinkedTreeMap map = (LinkedTreeMap) iterator.next();
Set<String> set = (map).keySet();
for (String key : set) {
jsonObject.addProperty(key, String.valueOf(map.get(key)));
}
jsonArray.add(jsonObject);
}

result = "{\"arrayInfo\":" + jsonArray.toString() + "}";
}

最后JsonTest的代码如下

1
2
3
4
5
6
7
8
9
10
11
12
public class JsonTest {

public static class MsgInfo{
private String content;
private String title;
private String teacher;
private long datetime;
}

private MsgInfo infos;
private ArrayList<****> arrayinfo;
}
Powered by Hexo & Theme Keep
Total words 22k Unique Visitor Page View