JSON串、JSON对象、Java对象的相互转换
对象类型转换2:
com.alibaba.fastjson.JSONObject时经常会用到它的转换方法,包括Java对象转成JSON串、JSON对象,JSON串转成java对象、JSON对象,JSON对象转换Java对象、JSON串等,使用方法总结如下
1、Java对象-->JSON对象
(JSONObject)JSONObject.toJSON(Java对象实例)
public classJSON2JavaTest{public static voidmain(String[] args) {
Student stu= new Student("公众号编程大道", "m", 2);//Java对象转化为JSON对象
JSONObject jsonObject =(JSONObject) JSONObject.toJSON(stu);
System.out.println("Java对象转化为JSON对象\n" + jsonObject);//{"name":"公众号编程大道","age":2,"sex":"m"}
}
}
2、Java对象-->JSON字符串
JSONObject.toJSONString(Java对象实例)
public classJSON2JavaTest{public static voidmain(String[] args) {
Student stu= new Student("公众号编程大道", "m", 2);//Java对象转换成JSON字符串
String stuString =JSONObject.toJSONString(stu);
System.out.println("Java对象转换成JSON字符串\n" + stuString);//{"age":2,"name":"公众号编程大道","sex":"m"}
}
}
3、JSON对象-->JSON字符串
JSONObject.toJSONString();
public classJSON2JavaTest{public static voidmain(String[] args) {
Student stu= new Student("公众号编程大道", "m", 2);//先转成JSON对象
JSONObject jsonObject =(JSONObject) JSONObject.toJSON(stu);//JSON对象转换为JSON字符串
String jsonString =jsonObject.toJSONString();
System.out.println("JSON对象转换为JSON字符串\n" + jsonString);//{"name":"公众号编程大道","age":2,"sex":"m"}
}
}
4、JSON对象-->Java对象
JSONObject.toJavaObject(JSON对象实例, Java对象.class);
public classJSON2JavaTest{public static voidmain(String[] args) {
Student stu= new Student("公众号编程大道", "m", 2);//先转成JSON对象
JSONObject jsonObject =(JSONObject) JSONObject.toJSON(stu);//JSON对象转换成Java对象
Student student = JSONObject.toJavaObject(jsonObject, Student.class);
System.out.println("JSON对象转换成Java对象\n" + student);//Student{name='公众号编程大道', sex='m', age=2}
}
}
5、JSON字符串-->JSON对象
JSONObject.parseObject(JSON字符串)
public classJSON2JavaTest{public static voidmain(String[] args) {
String stuString= "{\"age\":2,\"name\":\"公众号编程大道\",\"sex\":\"m\"}";//JSON字符串转换成JSON对象
JSONObject jsonObject1 =JSONObject.parseObject(stuString);
System.out.println("JSON字符串转换成JSON对象\n" + jsonObject1);//{"sex":"m","name":"公众号编程大道","age":2}
}
}
6、JSON字符串-->Java对象
JSONObject.parseObject(JSON字符串, Java对象.class);
public classJSON2JavaTest{public static voidmain(String[] args) {
String stuString= "{\"age\":2,\"name\":\"公众号编程大道\",\"sex\":\"m\"}";//JSON字符串转换成Java对象
Student student1 = JSONObject.parseObject(stuString, Student.class);
System.out.println("JSON字符串转换成Java对象\n" + student1);//Student{name='公众号编程大道', sex='m', age=2}
}
}