java对象与json对象间的相互转换

1.解析json字符串

将json字符串转换为json对象,然后再解析json对象:。
JSONObjectjsonObject = JSONObject.fromObject(jsonStr);
 根据json中的键得到它的值
Stringname = jsonObject.getString("name");
int age = jsonObject.getInt("age");

 
2.将json字符串转换为java对象
同样先将json字符串转换为json对象,再将json对象转换为java对象,如下所示。
JSONObjectobj = new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象
将json对象转换为java对象
Personjb = (Person)JSONObject.toBean(obj,Person.class);//将建json对象转换为Person对象

 
3.将java对象转换为json字符串

先将java对象转换为json对象,在将json对象转换为json字符串
JSONObjectjson = JSONObject.fromObject(obj);//将java对象转换为json对象
Stringstr = json.toString();//将json对象转换为字符串


实例代码:

package Test3;

public class Person {
	
	private int age;
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	private String name;
	public String toString() {
		return "Person [age=" + age + ", name=" + name + "]";
	}
	public Person(int age, String name) {
		super();
		this.age = age;
		this.name = name;
	}
	
	public Person(String personStr){
		
	}
	
	public Person(){
		
	}
}

package Test3;
import net.sf.json.JSONObject;


public class JsonToObject {

	/**
	 * @param args
	 */
	public void test(){
		
		System.out.println("将object对象,字符串转为json对象");
		
		Person person = new Person(1, "cgf");
		
		JSONObject json = JSONObject.fromObject(person);
		
		System.out.println(json);
		
		System.out.println("将字符串转成JSON对象,再转为自定义对象");
		
		String jsonString = "{" + "age" + ":1" + "," + "name" + ":" + "'wbj'" + "}";
		
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		
		System.out.println(jsonObject);
		
		Person person1 = (Person) JSONObject.toBean(jsonObject, Person.class);
		
		System.out.println("名字:"+person1.getAge() + "年龄:" + person1.getName());
		
		System.out.println("将Java对象转为json字符串");
		
		JSONObject json1 = JSONObject.fromObject(person);
		
		String jsonString1 = json1.toString();
		
		System.out.println(jsonString1);
		
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		JsonToObject json = new JsonToObject();
		
		json.test();
		
	}

}

java对象与json对象间的相互转换_第1张图片

你可能感兴趣的:(java对象与json对象间的相互转换)