Java中把json文件变成VO类的几种方式

json格式传输数据很爽,简单普及下json,从百科cp一句话如下:

 

 写道
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一个子集。

 

 也就是说大家用json做数据交换跟xml一样,本文基于json-lib版本为json-lib-2.4-jdk15.jar。目的是把一个json串转换成一个vo类。举例

{
    "id": "Elliotte",
    "name": "Harold"
}
把他转换成一个Student实例。查看代码提供方法如下:
public static Object toBean(JSONObject jsonObject)
public static Object toBean(JSONObject jsonObject, Class beanClass)
public static Object toBean(JSONObject jsonObject, Class beanClass, Map classMap)

public static Object toBean(JSONObject jsonObject, JsonConfig jsonConfig)
 使用方式如下:
public class Student {
	private String id;
	private String name;
	 
	public String getId() {
    	return id;
    }

	public void setId(String id) {
    	this.id = id;
    }

	public String getName() {
    	return name;
    }

	public void setName(String name) {
    	this.name = name;
    }

	@Override
    public String toString() {
	    return "Student [id=" + id + ", name=" + name + "]";
    }
}
 调用方式:
	public static void main(String[] args) {
		Map<String, Class<String>> classMap = new HashMap<String, Class<String>>();
		classMap.put("id", String.class);
		classMap.put("name", String.class);
		String content = "{ \"id\": \"Elliotte\", \"name\":\"Harold\" }";
		Student vo = new Student();
		try {
			vo = (Student) JSONObject.toBean(JSONObject.fromObject(content), Student.class);
			System.out.println("**Student:" + vo);
			vo = (Student) JSONObject.toBean(JSONObject.fromObject(content), Student.class,
			        classMap);
			System.out.println("**Student:" + vo);
			MorphDynaBean t = (MorphDynaBean) JSONObject.toBean(JSONObject.fromObject(content));
			System.out.println("**Student:" + t.get("id"));
			JsonConfig jc = new JsonConfig();
			jc.setRootClass(Student.class);
			vo = (Student) JSONObject.toBean(JSONObject.fromObject(content), jc);
			System.out.println("**Student:" + vo);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
 注意事宜:
1.vo类必须为public的否则跑属性缺失异常
 

你可能感兴趣的:(java)