使用fastjson将对象和字符串进行转换

依赖包:

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.54</version>
        </dependency>

 

范例代码:

 1 package org.study2.tools.json.fastjson;
 2 
 3 import com.alibaba.fastjson.JSON;
 4 import org.study2.bean.User;
 5 
 6 import java.util.ArrayList;
 7 import java.util.List;
 8 
 9 /**
10  * @Description: 使用fastjson将对象和字符串进行转换
11  **/
12 public class FastjsonDemo {
13 
14     public static void main(String[] args) {
15         //    测试数据
16         User userDemo = new User("tom", 25, "NO.1 street");
17         String jsonStr = "{\"name\":\"Lily\",\"age\":33,\"address\":\"NO.2 street\"}";
18 //    json转JavaBean
19         User user1 = JSON.parseObject(jsonStr, User.class);
20         System.out.println("1、json转JavaBean:" + user1);
21 
22 //    JavaBean转json
23         String jsonUser = JSON.toJSONString(userDemo);
24         System.out.println("2、JavaBean转json:" + jsonUser);
25 
26 //        将对象集合转换成为字符串
27         List<User> list = new ArrayList<>();
28         list.add(user1);
29         list.add(userDemo);
30         String jsonUsers = JSON.toJSONString(list);
31         System.out.println("3、将对象集合转换成为字符串:" + jsonUsers);
32 
33 //        将字符串转换成为对象集合
34         List<User> usersList = JSON.parseArray(jsonUsers,User.class);
35         System.out.println("4、将字符串转换成为对象集合:" + usersList);
36 
37     }
38     
39 }

 

运行结果:

1、json转JavaBean:User[name='Lily', age=33, address='NO.2 street']
2、JavaBean转json:{"address":"NO.1 street","age":25,"name":"tom"}
3、将对象集合转换成为字符串:[{"address":"NO.2 street","age":33,"name":"Lily"},{"address":"NO.1 street","age":25,"name":"tom"}]
4、将字符串转换成为对象集合:[User[name='Lily', age=33, address='NO.2 street'], User[name='tom', age=25, address='NO.1 street']]

 

posted @ 2019-01-08 11:20  星瑞  阅读(797)  评论(0编辑  收藏  举报