fastjson生成各种格式json串

本文json的jar包,采用阿里云的fastjson
官方github下载地址:https://github.com/alibaba/fastjson

样式一:json对象

1
2
3
4
{
"xxx": "xxx",
"yyy": "yyy"
}

代码实现示例

1
2
3
4
5
JSONObject json = new JSONObject();
json.put("xxx","xxxx");
json.put("yyy","yyy");
String str = json.toJSONString();
// {"xxx":"xxx"};

###样式二:json数组包含对象

1
2
3
4
5
6
7
[{
"xx": "xx",
"yy": "yy"
}, {
"xx": "yy",
"yy": "yy"
}]

代码实现示例

1
2
3
4
5
6
7
8
9
10
11
String[] key = {"张三","李四","王五","田七"}
int[] value = {32,23,33,36}
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < keyName.length; i++) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("name",key[i]);
jsonObj.put("age",value[i]);
jsonArray.add(jsonObj);
}
String str = jsonArray.toJSONString();
// [{"name":"张三","age":32},{"name":"李四","age":23}...]

样式三:json对象包含数组

1
2
3
4
5
6
7
8
{
"name": "xxx",
"interfaces": [{
"name": "yyy",
"untagged": true
}],
"remark": "xxxxx"
}

代码实现示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
JSONObject json = new JSONObject();
json.put("name","vlan_apitest");

JSONObject inter = new JSONObject();
inter.put("name","1.2");
inter.put("untagged",true);
JSONArray jsonArr = new JSONArray();
jsonArr.add(inter);

json.put("interfaces",jsonArr);
json.put("remark",666);

String str = json.toJSONString();
// {"interfaces":[{"untagged":true,"name":"1.2"}],"name":"vlan_apitest","remark":666}

本想整理所有有可能出现的样式,写完这几个才发现很简单,也没啥必要继续整理了,就这样吧!


-------------本文结束感谢您的阅读-------------
感觉文章不错,就赏个吧!
0%