上节,介绍了:
提供下载:
使用案例代码:
package com.what21.json2bean;
import org.json.JSONException;
import org.json.JSONObject;
import cn.hopegroup.util.json.Json2Bean;
public class Json2BeanDemo {
/**
* @param args
*/
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("\"username\":\"zhangsan\",");
sb.append("\"phone\":\"12312345678\",");
sb.append("\"desc\":\"www.what21.com\",");
sb.append("\"address\":\"山西省太原市\",");
sb.append("\"email\":\"1732482792@qq.com\",");
sb.append("\"name\":\"张三\",");
sb.append("\"age\": 30,");
sb.append("\"password\":passwd");
sb.append("}");
JSONObject userJson = null;
try {
userJson = new JSONObject(sb.toString());
} catch (JSONException e) {
e.printStackTrace();
}
// 将JSON转换成对象
User user = (User)Json2Bean.to(User.class, userJson);
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println(user.getName());
// 不支持int类型,只支持字符串类型
System.out.println(user.getAge());
System.out.println(user.getEmail());
System.out.println(user.getPhone());
System.out.println(user.getAddress());
System.out.println(user.getDesc());
}
}