1. 实体类或集合转JSON串
String jsonString = JSONObject.toJSONString(实体类);
2.JSON串转JSONObject
JSONObject jsonObject = JSONObject.parseObject(jsonString);
3.JSON串转实体类
实体类 javaBean = JSON.parseObject(json, 实体类.class);
4.JSON串转带泛型的List的集合
List<实体类或其他泛型> list = JSON.parseObject(json, new TypeReference<List<实体类或其他泛型>>(){});原文地址:https://blog.csdn.net/aa494661239/article/details/80515420
1 <dependency> 2 <groupId>com.alibaba</groupId> 3 <artifactId>fastjson</artifactId> 4 <version>1.2.7</version> 5 </dependency>
首先引入相关jar包,
假设有一个实体类User
public class User{ private int id; private String name; }
然后通过fastJson进行类型转换
public static void main(String[] args){ String userString = "{"id":1,"name","lz"}"; JSONObject userJson = JSONObject.parseObject(userString); User user = JSON.toJavaObject(userJson,User.class); }