JAVA对象与JSON转换的各种方法-fastjson

1 <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
2 <dependency>
3     <groupId>com.alibaba</groupId>
4     <artifactId>fastjson</artifactId>
5     <version>1.2.62</version>
6 </dependency>

 1 import com.alibaba.fastjson.JSONObject; 

1、Java对象–>JSON对象

 1 public class JSONTest{
 2     public static void main(String[] args) {
 3         User user = new User("张三", "", 18);
 4  
 5         //Java对象转化为JSON对象
 6         JSONObject jsonObject = (JSONObject) JSONObject.toJSON(user);
 7         System.out.println("Java对象转化为JSON对象\n" + jsonObject);//{"name":"张三","age":18,"sex":"男"}
 8         
 9     }
10 }

2、Java对象–>JSON字符串

1 public class JSONTest{
2     public static void main(String[] args) {
3         USer user = new User("张三", "男", 18);
4  
5         //Java对象转换成JSON字符串
6         String userStr = JSONObject.toJSONString(user);
7         System.out.println("Java对象转换成JSON字符串\n" + userStr);//{"age":18,"name":"张三","sex":"男"}
8     }
9 }

3、JSON对象–>JSON字符串

 1 public class JSONTest{
 2     public static void main(String[] args) {
 3         User user = new User("张三", "男", 18);
 4  
 5         //先转成JSON对象
 6         JSONObject jsonObject = (JSONObject) JSONObject.toJSON(user);
 7  
 8         //JSON对象转换为JSON字符串
 9         String jsonString = jsonObject.toJSONString();
10         System.out.println("JSON对象转换为JSON字符串\n" + jsonString);//{"name":"张三","age":18,"sex":"男"}
11  
12     }
13 }

4、JSON对象–>Java对象

 1 public class JSONTest{
 2     public static void main(String[] args) {
 3         User user1 = new User("张三", "男", 18);
 4  
 5         //先转成JSON对象
 6         JSONObject jsonObject = (JSONObject) JSONObject.toJSON(user1);
 7         
 8         //JSON对象转换成Java对象
 9         User user = JSONObject.toJavaObject(jsonObject, User.class);
10         System.out.println("JSON对象转换成Java对象\n" + user);//User{name='张三', sex='男', age=18}
11     }
12 }

5、JSON字符串–>JSON对象

1 public class JSONTest{
2     public static void main(String[] args) {
3         String userStr = "{\"age\":18,\"name\":\"张三\",\"sex\":\"男\"}";
4  
5         //JSON字符串转换成JSON对象
6         JSONObject jsonObject1 = JSONObject.parseObject(userStr);
7         System.out.println("JSON字符串转换成JSON对象\n" + jsonObject1);//{"sex":"男","name":"张三","age":18}
8     }
9 }

6、JSON字符串–>Java对象

1 public class JSONTest{
2     public static void main(String[] args) {
3         String userStr = "{\"age\":18,\"name\":\"张三\",\"sex\":\"男\"}";
4  
5         //JSON字符串转换成Java对象
6         User user = JSONObject.parseObject(userStr, User.class);
7         System.out.println("JSON字符串转换成Java对象\n" + user);//user {name='张三', sex='男', age=18}
8     }
9 }

 

posted @ 2022-08-21 12:25  勤快的懒羊羊  阅读(2689)  评论(0编辑  收藏  举报