目的:把一个json数据转成java对象

需要准备一个:fastJson.jar包

一个简单的对象

package test.domain;

 

public class User {

	private String name;

	private String age;

	public String getName() {

		return name;
	}

	public void setName(String name) {

		this.name = name;
	}

	public String getAge() {

		return age;
	}

	public void setAge(String age) {

		this.age = age;
	}

	@Override

	public String toString() {

		return "User [name=" + name + ", age=" + age + "]";

	}
	
}

测试

package test.test;

import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import test.domain.User;

public class demo {
	public static void main(String[] args) {		

//		String json = "{'name':'z3','age':'20'}";
//		User u =  JSON.parseObject(json,User.class);	
//		System.out.println(u);

		//转成map再从map中获取相对应得数据

//		String json_1 = "{'id':'1','user':{'name':'z3','age':'20'}}";
//		Map map = JSON.parseObject(json_1);	
//		String aa =  map.get("user").toString();
//		User u =  JSON.parseObject(aa,User.class);	
//		System.out.println(u);	

		

		//转成json对象再从map中获取相对应得数据
		String json_2 = "{'id':'1','user':{'name':'z3','age':'20'}}";
		JSONObject jsonObject = JSONObject.parseObject(json_2);
		String string = jsonObject.getString("user");	

	
		User u =  JSON.parseObject(string,User.class);	
		System.out.println(u);	
	}
}