<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
1.Java对象的转换
定义Java对象
UserInfo userInfo = new UserInfo();
userInfo.setName("zhang");
userInfo.setDept("yanfa");
userInfo.setGender("女");
userInfo.setAge(11);
1.1Java对象->String
String userStr = JSON.toJSONString(userInfo);
1.2Java对象->JSON对象
JSONObject userStrJson2 = (JSONObject) JSON.toJSON(userInfo);
2.JSON对象的转换
定义JSON对象
UserInfo userInfo = new UserInfo();
userInfo.setName("zhang");
userInfo.setDept("yanfa");
userInfo.setGender("女");
userInfo.setAge(11);
JSONObject json = (JSONObject) JSON.toJSON(userInfo);
2.1 JSON对象->Java对象
UserInfo user = JSONObject.toJavaObject(json, UserInfo.class);
2.2 JSON对象->String
String str = JSONObject.toJSONString(json);
3.String的转换
定义String串
String str = "{\"gender\":\"女\",\"name\":\"张三\",\"dept\":\"研发\",\"age\":\"22\"}";
3.1 String->Java对象
UserInfo user = JSONObject.parseObject(str, UserInfo.class);
3.2 String->JSON对象
JSONObject json = JSONObject.parseObject(str);
4.List的转换
定义List对象
List<UserInfo> userList = new ArrayList<UserInfo>();
UserInfo user1 = new UserInfo();
user1.setName("zhang");
user1.setDept("yanfa");
user1.setGender("女");
user1.setAge(11);
UserInfo user2 = new UserInfo();
user2.setName("zhang");
user2.setDept("yanfa");
user2.setGender("女");
user2.setAge(11);
userList.add(user1);
userList.add(user2);
4.1 List->String
String str1 = JSON.toJSONString(userList);
4.2 List->JSONObject->String
String str2 = JSON.toJSON(userList).toString();
4.3 String->JSONArray
JSONArray array = JSONObject.parseArray(str1);