Json数据和对象互转
1、创建UserTest类
package com.cppdy; public class UserTest { private String name; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "User [name=" + name + ", sex=" + sex + "]"; } }
2、创建JsonTest1类测试互转
package com.cppdy; import com.alibaba.fastjson.JSONObject; public class JsonTest1 { public static void main(String[] args) { JSONObject ob = new JSONObject(); ob.put("name", "吹泡泡的魚"); ob.put("sex", "男"); UserTest user = JSONObject.toJavaObject(ob, UserTest.class); System.out.println("JSON转Object:" + user.toString()); UserTest u = new UserTest(); u.setName("cppdy"); u.setSex("nan"); String jsonString = JSONObject.toJSONString(u); System.out.println("Object转JSON:" + jsonString); } }