java中json转化成对象,对象转化成json

 首先要带入第三方工具类jar包 gson

1,普通类:

public void test() {
		//1、创建Gson对象
		Gson gson = new Gson();
		User user = new User(1, "liujinghan", "123456", "[email protected]");
		//2、调用toJson(Object)将对象转为字符串
		String json = gson.toJson(user);
		//{"id":1,"username":"liujinghan","password":"123456","email":"[email protected]"}
		System.out.println(json);
		//3、将json字符串封装为java对象[json字符串 的属性名要和javabean的属性一样]
		User user2 = gson.fromJson(json, User.class);
		System.out.println(user2);
	}

2,Map数组形式

public void test1() {
		Map map = new HashMap();
		map.put("name", "laolu");
		map.put("age", 18);
		Gson gson = new Gson();
		String json = gson.toJson(map);
		System.out.println(json);
		//将json字符串转为map   Gson将int类型数据转换时会转为double类型
		Map map2 = gson.fromJson(json, Map.class);
		System.out.println(map2);
		
	}

3,List数组的形式:

public void test2() {
		List list = new ArrayList();
		list.add(new User(1, "liujinghan1", "123456", "[email protected]"));
		list.add(new User(2, "liujinghan2", "123456", "[email protected]"));
		list.add(new User(3, "liujinghan3", "123456", "[email protected]"));
		list.add(new User(4, "liujinghan4", "123456", "[email protected]"));
		Gson gson = new Gson();
		//会将list转为一个json数组,每个元素就对应一个java对象
		String json = gson.toJson(list);
		System.out.println(json);
		List list2 = gson.fromJson(json,List.class);
		System.out.println(list2.get(0));

 

你可能感兴趣的:(javaweb)