首页 > 代码库 > Java对象和集合与Json之间的互相转换

Java对象和集合与Json之间的互相转换

        总结一下Java对象和集合与Json之间的互相转换:

        1、创建的User类:

package com.ghj.packageofdomain;

public class User {
	
	private int id;
	private String name;
	private String gender;

	public User() {

	}

	public User(int id, String name, String gender) {
		this.id = id;
		this.name = name;
		this.gender = gender;
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}

	@Override
	public String toString() {
		return "id=" + id + ",name=" + name + ",gender=" + gender;
	}
}
        2、Java对象和集合与Json之间的互相转换:
        i、Java对象与Json之间的互相转换:

package com.ghj.packageoftest;

import net.sf.json.JSONObject;

import com.ghj.packageofdomain.User;

public class Test{

	public static void main(String[] args) {
		System.out.println(objectToJsonString());
		jsonStringToObject(objectToJsonString());
	}
	
	/**
	 * 将Java对象转换为Json字符串
	 * 
	 * @author 高焕杰
	 */
	static String objectToJsonString(){
		JSONObject jsonObject = JSONObject.fromObject(new User(1, "张三", "男"));
	    return jsonObject.toString();
	}
	
	/**
	 * 将Json字符串转换为Java对象
	 * 
	 * @author 高焕杰
	 */
	static void jsonStringToObject(String jsonString){
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		User user = (User)JSONObject.toBean(jsonObject, User.class);
		System.out.println(user);
	}
}
        ii、Java集合与Json之间的互相转换:




Java对象和集合与Json之间的互相转换