闲来无事,偶然想到fastjson封装对象的事情,于是便做了一个测试,看来以后可以少些几个工具类了
实体:
package com.site.utils; import java.util.List; /** * Create by szw on 2017/11/24 10:17 */ public class Life { private String name;//姓名 private int age;//年龄 private String country;//国家 private List<String> friend; public Life() { } @Override public String toString() { return "Life{" + "name='" + name + '\'' + ", age=" + age + ", country='" + country + '\'' + ", friend=" + friend + '}'; } public String getName() { return name; } public Life(String name, int age, String country, List<String> friend) { this.name = name; this.age = age; this.country = country; this.friend = friend; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public List<String> getFriend() { return friend; } public void setFriend(List<String> friend) { this.friend = friend; } }
测试:
package com.site.utils; import ch.qos.logback.core.net.SyslogOutputStream; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Create by szw on 2017/11/24 11:16 */ public class ParseBean { public static void main(String[] args) { Map<String, Object> hashMap = new HashMap<>(); hashMap.put("name", "诸葛亮"); hashMap.put("age", 27); hashMap.put("country", "蜀"); hashMap.put("friend", new ArrayList<>()); String s = JSON.toJSONString(hashMap); System.out.println(s); Life life = JSON.parseObject(s, Life.class); System.out.println(life.toString()); } }