FastJson:json字符串与Java对象转换
FastJson:json字符串与Java对象转换
对象实体类(省略get set toString)
class User {
String name;
String age;
String sex;
public User(){}
public User(String name, String age, String sex) {
this.name = name;
fastjson字符串转数组this.age = age;
this.sex = sex;
}
}
1.1、对象转json字符串
User user1 = new User("丽丽","24","⼥");
String jsonUser = JSONString(user1);
System.out.println(jsonUser);//{"age":"24","name":"丽丽","sex":"⼥"}
1.2、 json字符串转对象
JSONObject jsonStr = JSONObject.parseObject(jsonUser);
User user2 = JavaObject(jsonStr,User.class);
//其他
DataStore<ResidentDTO> residentDTODataStore = JSONObject.parseObject(String.valueOf(jsonStr), new TypeReference<DataStore<ResidentDTO>>() {});
2.1、List转json字符串
List<User> users = new ArrayList<>();
User userTest1 = new User("李四", "22","男");
User userTest2 = new User("王五", null,"男");
users.add(userTest1);
users.add(userTest2);
String jsonUsers = JSONString(users);//[{"age":"22","name":"李四","sex":"男"},{"name":"王五","sex":"男"}]
2.2、json字符串转List
List<User> userlist = JSON.parseArray(jsonUsers,User.class);//[User{name='李四', age='22', sex='男'},
User{name='王五', age='null', sex='男'}]
3.1、Map 转json字符串
Map<String, Object> map = new HashMap();
map.put("user",user1);
String mapJson = JSONString(map);//{"user":{"age":"24","name":"丽丽","sex":"⼥"}}
3.2、json字符串转Map
JSONObject jsonMap = JSONObject.parseObject(mapJson);
Map<String, Object> map1 = JavaObject(jsonMap,Map.class);//{"user":{"sex":"⼥","name":"丽丽","age":"24"}}
4、FastJson maven依赖
<!-- mvnrepository/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.75</version>
</dependency>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。