public class PojoToArray {
public static void main(String[] args) {
User user = User.builder().username("username").name("name").build();
// pojo 转 map
Map<String,Object> map = JSONObject.<Map<String, Object>>parseObject(JSON.toJSONString(user), Map.class);
map.put("1","1");
map.keySet().forEach(key -> {
System.out.println("pojo 转 map ==>" + key + "==>" + map.get(key));
});
// pojo 转 josn
// 方法一
JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(user));
// 方法二
JSONObject jsonObject1 = JSONObject.parseObject(JSON.toJSONString(user));
System.out.println("pojo 转 josn == >" + jsonObject.toJSONString());
// map 转 pojo
HashMap<String, Object> map1 = new HashMap<>();
map1.put("1",1);
map1.put("username","username");
map1.put("name","name");
// 方式1
User user1 = User.builder().build();
map1.forEach((key,value) -> {
if (key.equals("username")){
user1.setUsername((String) value);
}
if (key.equals("name")){
user1.setName((String) value);
}
});
System.out.println("map 转 pojo == >" + user1.toString());
// 方式二
User user2 = JSON.parseObject(JSON.toJSONString(map1),User.class);
System.out.println("map 转 pojo == >" + user2.toString());
// map 转 list
// 方式一
ArrayList<Object> objects = new ArrayList<>();
map1.forEach((key,value) -> {
objects.add(value);
});
System.out.println("map 转 list == >" + JSON.toJSONString(objects));
// 方式二
Collection<Object> values = map1.values();
System.out.println("map 转 list == >" + JSON.toJSONString(values));
// map 转 JSONObject
JSONObject jsonObject2 = JSON.parseObject(JSON.toJSONString(map1));
System.out.println("map 转 JSONObject == >" + JSON.toJSONString(jsonObject2));
}
}```
05-13
818