json与对象、集合、map的转换

package test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

// 需要导入gson包
public class Test {
	private Integer id;
	private String name;
	public Integer getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "Test [id=" + id + ", name=" + name + "]";
	}
	
	
	public static void main(String[] args) {
//		System.out.println(beanToJson());
//		System.out.println(jsonToBean().toString());
//		System.out.println(jsonToBean().getId());
//		System.out.println(jsonToBean().getName());
//		System.out.println(listToJson());
//		List<Test> testList = jsonToListBean();
//		for (Test test : testList) {
//			System.out.println(test.toString());
//		}
//		System.out.println(mapToJson());
		Map<String, Test> map = jsonToMapBean();
		for (Test test : map.values()) {
			System.out.println(test.toString());
		}
	}
	
	// java对象转json
	public static String beanToJson(){
		Test test = new Test();
		test.setId(1);
		test.setName("wjj");
		Gson gson = new Gson();
		String json = gson.toJson(test);
		return json;
	}
	// json转成java对象
	public static Test jsonToBean(){
		String json = beanToJson();
		Gson gson = new Gson();
		Test test = gson.fromJson(json, Test.class);
		return test;
	}
	// list转json
	public static String listToJson(){
		List<Test> testList = new ArrayList<Test>();
		for (int i = 1; i <= 3; i++) {
			Test test = new Test();
			test.setId(i);
			test.setName("haha:"+i);
			testList.add(test);
		}
		Gson gson = new Gson();
		String json = gson.toJson(testList);
		return json;
	}
	// json转list
	public static List<Test> jsonToListBean(){
		String json = listToJson();
		Gson gson = new Gson();
		List<Test> testList = gson.fromJson(json, new TypeToken<List<Test>>(){}.getType());
		return testList;
	}
	// map转json 
	public static String mapToJson(){
		Map<String, Test> testMap = new HashMap<String, Test>();
		for (int i = 1; i <= 3; i++) {
			Test test = new Test();
			test.setId(i);
			test.setName("haha:"+i);
			testMap.put("key"+i, test);
		}
		Gson gson = new Gson();
		String json = gson.toJson(testMap);
		return json;
	}
	// json转map
	public static Map<String, Test> jsonToMapBean(){
		String json = mapToJson();
		Gson gson = new Gson();
		Map<String, Test> map = gson.fromJson(json, new TypeToken<Map<String, Test>>(){}.getType());
		return map;
	}

	
}

猜你喜欢

转载自blog.csdn.net/sinat_37795871/article/details/84582229