1、Java對象-->JSON對象
(JSONObject)JSONObject.toJSON(Java對象實例)
1 public class JSON2JavaTest{
2 public static void main(String[] args) {
3 Student stu = new Student("公眾號編程大道", "m", 2);
4
5 //Java對象轉化為JSON對象
6 JSONObject jsonObject = (JSONObject) JSONObject.toJSON(stu);
7 System.out.println("Java對象轉化為JSON對象\n" + jsonObject);//{"name":"公眾號編程大道","age":2,"sex":"m"}
8
9 }
10 }
2、Java對象-->JSON字符串
JSONObject.toJSONString(Java對象實例)
1 public class JSON2JavaTest{
2 public static void main(String[] args) {
3 Student stu = new Student("公眾號編程大道", "m", 2);
4
5 //Java對象轉換成JSON字符串
6 String stuString = JSONObject.toJSONString(stu);
7 System.out.println("Java對象轉換成JSON字符串\n" + stuString);//{"age":2,"name":"公眾號編程大道","sex":"m"}
8 }
9 }
3、JSON對象-->JSON字符串
JSONObject.toJSONString();
1 public class JSON2JavaTest{
2 public static void main(String[] args) {
3 Student stu = new Student("公眾號編程大道", "m", 2);
4
5 //先轉成JSON對象
6 JSONObject jsonObject = (JSONObject) JSONObject.toJSON(stu);
7
8 //JSON對象轉換為JSON字符串
9 String jsonString = jsonObject.toJSONString();
10 System.out.println("JSON對象轉換為JSON字符串\n" + jsonString);//{"name":"公眾號編程大道","age":2,"sex":"m"}
11
12 }
13 }
4、JSON對象-->Java對象
JSONObject.toJavaObject(JSON對象實例, Java對象.class);
public class JSON2JavaTest{
public static void main(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字符串)
1 public class JSON2JavaTest{
2 public static void main(String[] args) {
3 String stuString = "{\"age\":2,\"name\":\"公眾號編程大道\",\"sex\":\"m\"}";
4
5 //JSON字符串轉換成JSON對象
6 JSONObject jsonObject1 = JSONObject.parseObject(stuString);
7 System.out.println("JSON字符串轉換成JSON對象\n" + jsonObject1);//{"sex":"m","name":"公眾號編程大道","age":2}
8 }
9 }
6、JSON字符串-->Java對象
JSONObject.parseObject(JSON字符串, Java對象.class);
1 public class JSON2JavaTest{
2 public static void main(String[] args) {
3 String stuString = "{\"age\":2,\"name\":\"公眾號編程大道\",\"sex\":\"m\"}";
4
5 //JSON字符串轉換成Java對象
6 Student student1 = JSONObject.parseObject(stuString, Student.class);
7 System.out.println("JSON字符串轉換成Java對象\n" + student1);//Student{name='公眾號編程大道', sex='m', age=2}
8 }
9 }

