需要导入的包
import com.alibaba.fastjson.JSONObject;
例1:
要处理的json字符串:
{
“gradle”:“高一”,
“number”:“2”,
“people”:[{“name”:“张三”,“age”:“15”,“phone”:“123456”},
{“name”:“李四”,“age”:“16”,“phone”:“78945”}]
}
下面对此json字符串进行常见的解析和转换,
代码如下:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import java.util.*;
public class Test {
public static void main(String[] args) {
String str="\n" +
"{\n" +
"\"gradle\":\"高一\",\n" +
"\"number\":\"2\",\n" +
"\"people\":[{\"name\":\"张三\",\"age\":\"15\",\"phone\":\"123456\"},\n" +
" {\"name\":\"李四\",\"age\":\"16\",\"phone\":\"78945\"}]\n" +
"}";
JSONObject strJson=JSONObject.parseObject(str);//字符串转json对象
System.out.println("1:"+strJson.toString());
Map<String, Object> map = JSONObject.parseObject(str, new TypeReference<Map<String, Object>>() {});//json字符串转Map
System.out.println("2:"+map.get("people").toString());
String str1=JSON.toJSONString(strJson);//JSONObject转字符串
System.out.println("3:"+str1);
String gradle=(String)strJson.get("gradle");
System.out.println("4:"+gradle);
strJson.put("sex","男");//JSONObject中添加sex字段
System.out.println("5:"+strJson.toString());
JSONArray peopleArray = strJson.getJSONArray("people");//JSONObject中获取数组people字段
System.out.println("6:"+peopleArray.toString());
for(int i=0;i<peopleArray.size();i++){
JSONObject job = peopleArray.getJSONObject(i); // 遍历 peopleArray 数组,把每一个对象转成 json 对象
System.out.println("7:"+job.get("name")) ; // 得到 每个对象中的属性值
}
//创建JSON数组向strJson中加入gradle
JSONArray jsonArray = new JSONArray();
JSONObject grade=new JSONObject();//分数
JSONObject grade1=new JSONObject();//分数
grade.put("语文","80") ;
grade.put("数学","90") ;
grade1.put("地理","70") ;
grade1.put("英语","60") ;
jsonArray.add(grade);
jsonArray.add(grade1);
strJson.put("gradle", jsonArray);//向strJson中加入gradle数组
System.out.println("8:"+strJson.toString()) ;
//将people这个json数组转化为List<Map<String,String>>
String people = String.valueOf(strJson.getJSONArray("people"));
List<Map<String,String>> listObjectFir = (List<Map<String,String>>) JSONArray.parse(people);
System.out.println("9:"+listObjectFir.toString()) ;
Map<String,String> perpleMap = listObjectFir.get(0);
System.out.println("9-1:"+perpleMap.get("name")) ;
}
}
输出结果:
1:{"gradle":"高一","number":"2","people":[{"phone":"123456","name":"张三","age":"15"},{"phone":"78945","name":"李四","age":"16"}]}
2:[{"phone":"123456","name":"张三","age":"15"},{"phone":"78945","name":"李四","age":"16"}]
3:{"gradle":"高一","number":"2","people":[{"phone":"123456","name":"张三","age":"15"},{"phone":"78945","name":"李四","age":"16"}]}
4:高一
5:{"gradle":"高一","number":"2","sex":"男","people":[{"phone":"123456","name":"张三","age":"15"},{"phone":"78945","name":"李四","age":"16"}]}
6:[{"phone":"123456","name":"张三","age":"15"},{"phone":"78945","name":"李四","age":"16"}]
7:张三
7:李四
8:{"gradle":[{"数学":"90","语文":"80"},{"英语":"60","地理":"70"}],"number":"2","sex":"男","people":[{"phone":"123456","name":"张三","age":"15"},{"phone":"78945","name":"李四","age":"16"}]}
9:[{"phone":"123456","name":"张三","age":"15"},{"phone":"78945","name":"李四","age":"16"}]
9-1:张三
注意:
当使用JSON.toJSONString()来将对象转化成JSON字符串时,有可能对象里面为空,比如:
Map<String,String> map=new HashMap<>();
map.put("测试1",null);
map.put("测试2","hello");
System.out.println(JSON.toJSONString(map)) ;
//输出结果:{"测试2":"hello"}
可见,测试1的值为空没有输出,解决方法:
Map<String,String> map=new HashMap<>();
map.put("测试1",null);
map.put("测试2","hello");
System.out.println(JSON.toJSONString(map, SerializerFeature.WriteMapNullValue)) ;
//输出结果:{"测试1":null,"测试2":"hello"}
JSON.toJSONString(map, SerializerFeature.WriteMapNullValue) 指定序列化方式就打印出来了。当然不仅仅map,还有List等,具体可以看下面的文章或fastjson的JSON.toJSONString原码。
例2:
import com.alibaba.fastjson.JSONArray;
import java.util.*;
public class Test {
public static void main(String[] args) {
JSONArray array = new JSONArray();
Map<String, Object> sourceAsMap = new HashMap<>();
sourceAsMap.put("姓名", "张三");
sourceAsMap.put("年龄", 15);
array.add(sourceAsMap);
Map<String, Object> sourceAsMap1 = new HashMap<>();
sourceAsMap1.put("姓名", "李四");
sourceAsMap1.put("年龄", 50);
array.add(sourceAsMap1);
String retStr = array.toJSONString();
System.out.println(retStr);
}
}
输出结果:
[{"姓名":"张三","年龄":15},{"姓名":"李四","年龄":50}]
例3:
String str = "\n" +
"{\n" +
"\"gradle\":\"高一\",\n" +
"\"number\":\"2\",\n" +
"\"name\":[\"李四\",\"张三\",\"王五\"]\n" +
"}";
JSONObject strJson = JSONObject.parseObject(str);//字符串转json对象
JSONArray peopleArray = strJson.getJSONArray("name");
String people = String.valueOf(peopleArray);
List<String> list =(List)JSONArray.parse(people);//json数组转list数组
System.out.println("1.json数组转list数组:"+list);
peopleArray.add("赵六");
System.out.println("2.json数组里添加赵六:"+peopleArray);
System.out.println("3.遍历:");
for (int i=0;i<peopleArray.size();i++){
String name= peopleArray.getString(i);
System.out.println(name);
}
输出:
1.json数组转list数组:["李四","张三","王五"]
2.json数组里添加赵六:["李四","张三","王五","赵六"]
3.遍历:
李四
张三
王五
赵六
判断json里的属性是数组还是数值类型:
通过下面的代码判断某一字段的类型:
Object jsobj = JSONObject.parse(jsonStr);
if(jsobj instanceof JSONArray){
//JSONArray
}
if(jsobj instanceof JSONObject){
//JSONObject
}
如判断customer_act是否是数组类型:
String str = "{\"customer_no\":\"106700277539\",\"customer_id\":106700277539,\"customer_act\":[\"106\",\"119\",\"121\",\"120\",\"129\",\"134\",\"136\",\"137\",\"138\",\"141\",\"148\",\"149\",\"150\",\"158\",\"170\",\"174\",\"179\",\"189\"]}";
JSONObject jsonObject = JSONObject.parseObject(str);
String act=jsonObject.getString("customer_act");
Object jsobj = JSONObject.parse(act);
if(jsobj instanceof JSONArray){
System.out.println("customer_act是数组");
}
if(jsobj instanceof JSONObject){
System.out.println("customer_act是数值");
}
输出:customer_act是数组
String str ="{\"customer_no\":\"106700279901\",\"customer_id\":106700279901,\"customer_act\":153}";
JSONObject jsonObject = JSONObject.parseObject(str);
String act=jsonObject.getString("customer_act");
Object jsobj = JSONObject.parse(act);
if(jsobj instanceof JSONArray){
System.out.println("customer_act是数组");
}
if(jsobj instanceof JSONObject){
System.out.println("customer_act是数值");
}
输出:customer_act是数值
去除json字符串里的所有反斜杠:
使用fastjson的Json.toJsonString方法时出现多余反斜杠,可通过StringEscapeUtils.unescapeEcmaScript去除,需要导入commons-text-1.9.jar
下载网址:https://mvnrepository.com/artifact/org.apache.commons/commons-text/1.9
String str1 = "{\"resourceId\":\"dfead70e4ec5c11e43514000ced0cdcaf\",\"properties\":{\"process_id\":\"process4\",\"name\":\"\",\"documentation\":\"\",\"processformtemplate\":\"\"}}";
String tmp = StringEscapeUtils.unescapeEcmaScript(str1);
System.out.println("tmp:" + tmp);
输出:
tmp:{"resourceId":"dfead70e4ec5c11e43514000ced0cdcaf","properties":{"process_id":"process4","name":"","documentation":"","processformtemplate":""}}
JSON序列化参考文章:
JSON.toJSONString中序列化空字符串遇到的坑
为什么设置了SerializerFeature.WriteNullStringAsEmpty,fastjson字段为null时不输出空字符串?
其他常见的json处理可参考如下文章:
FastJson中JSONObject用法及常用方法总结
java中json的使用和解析()
关于JSON.parseObject 和 JSON.toJSONString 实例
JSON数组形式字符串转换为List<Map<String,String>>的8种方法