依赖包:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
范例代码:
package org.study2.tools.json.fastjson; import com.alibaba.fastjson.JSON;
import org.study2.bean.User; import java.util.ArrayList;
import java.util.List; /**
* @Description: 使用fastjson将对象和字符串进行转换
**/
public class FastjsonDemo { public static void main(String[] args) {
// 测试数据
User userDemo = new User("tom", 25, "NO.1 street");
String jsonStr = "{\"name\":\"Lily\",\"age\":33,\"address\":\"NO.2 street\"}";
// json转JavaBean
User user1 = JSON.parseObject(jsonStr, User.class);
System.out.println("1、json转JavaBean:" + user1); // JavaBean转json
String jsonUser = JSON.toJSONString(userDemo);
System.out.println("2、JavaBean转json:" + jsonUser); // 将对象集合转换成为字符串
List<User> list = new ArrayList<>();
list.add(user1);
list.add(userDemo);
String jsonUsers = JSON.toJSONString(list);
System.out.println("3、将对象集合转换成为字符串:" + jsonUsers); // 将字符串转换成为对象集合
List<User> usersList = JSON.parseArray(jsonUsers,User.class);
System.out.println("4、将字符串转换成为对象集合:" + usersList); } }
运行结果:
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']]