前言
请各大网友尊重本人原创知识分享,谨记本人博客:南国以南i、
提示:以下是本篇文章正文内容,下面案例可供参考
背景
在我们开发过程中很多地方涉及JSON数据处理转换,以下列举基本使用实例
public class Test {
public static void main(String[] args) {
/*alibaba.fastjson 应用转换*/
//字符串与集合互转
strToCollection();
//JSON与对象互转
jsonToTarget();
List list = new ArrayList();
System.out.println(typeOf(list));
}
//字符串与集合互转
public static void strToCollection() {
//字符串数组
String taskId = "[\"1001\",\"1002\"]";
//将字符串数组转List
List<String> item = JSON.parseArray(taskId, String.class);
item.forEach(i -> {
System.out.println(i);
});
//字符串json
String param = "{\"phone\":\"15800329194\",\"name\":\"张三\"}";
//将字符串转Map
Map<String, String> paramMap = JSON.parseObject(param, Map.class);
paramMap.forEach((key, value) -> {
System.out.println("key:" + key + "---value:" + value);
});
//将Map转json字符串
String strParam = JSON.toJSONString(paramMap);
System.out.println(strParam);
}
//JSON与对象互转
public static void jsonToTarget() {
Student stu = new Student("测试", "12", 1);
//Java对象转化为JSON对象
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(stu);
System.out.println("Java对象转化为JSON对象\n" + jsonObject);
//Java对象转换成JSON字符串 或者JSON.toJSONString(stu); JSONObject继承了JSON
String stuString = JSONObject.toJSONString(stu);
System.out.println("Java对象转换成JSON字符串\n" + stuString);
//JSON字符串转换成Java对象
String stuStringTo = "[{\"age\":\"12\",\"name\":\"测试\",\"sex\":1}]";
List<Student> studentList = JSONObject.parseArray(stuStringTo, Student.class);
System.out.println("JSON字符串转换成Java对象list\n" + studentList);
}
//类型判断
public static String typeOf(Object obj) {
String type = "";
if (obj instanceof String) {
type = "String类型";
} else if (obj instanceof Integer) {
type = "Integer类型";
} else if (obj instanceof List) {
type = "List类型";
}
return type;
}
//内部类
static class Student {
//姓名
private String name;
//年龄
private String age;
//性别
private int sex;
public Student(String name, String age, int sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
}
}
总结
我是南国以南i记录点滴每天成长一点点,学习是永无止境的!转载请附原文链接!!!