Google-Gson Demo

Gson源于google
Gson这个Java类库可以把Java对象转换成JSON,也可以把JSON字符串转换成一个相等的Java对象。Gson支持任意复杂Java对象包括没有源代码的对象。

Gson目标
1、提供简单的toJson()和fromJson()方法的java对象转换为JSON,反之亦然
2、允许预先存在不可改变的对象被转换为和从JSON
3、广泛支持的java泛型
4、允许自定义对象的意见
5、支持任意复杂的对象(深层次结果和继承泛型类型的广泛使用)

一、声明要进行json输入/输出的对象
package com.zhl.gson;

import com.google.gson.annotations.Expose;

public class User {
	@Expose
	private Long id;
	
	@Expose
	private String name;
	
	@Expose
	private User next;

	public Long getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public User getNext() {
		return next;
	}

	public void setNext(User next) {
		this.next = next;
	}
}


二、关于对象转换为json、或者json转换为对象
package com.zhl.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class Test {

	public static void main(String[] args) {
		User user = new User();
		user.setId(1001L);
		user.setName("zhenlging");
		User next = new User();
		next.setId(1002L);
		next.setName("yangyang");
		user.setNext(next);
		
		GsonBuilder builder = new GsonBuilder();

		//不转换没有@Expose注解的字段
		builder.excludeFieldsWithoutExposeAnnotation();
		Gson gson = builder.create();
		
		//将对象转换为JSON字符串
		String sUserString = gson.toJson(user);
		System.out.println(sUserString);
		
		User user2 = gson.fromJson(sUserString, User.class);
		System.out.println("USER_ID: " + user2.getId() + "    USER_NAME:" + user2.getNext().getName());
		
	}
	
}


三、集合转换为json或者json转换为集合
package com.zhl.gson;

import java.util.HashMap;
import java.util.Map;

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

public class MapTest {
  public static void main(String[] args) {
	
	  User user1 = new User();
	  user1.setId(1001L);
	  user1.setName("zhengling");
	  User user2 = new User();
	  user2.setId(1002L);
	  user2.setName("yangyang");
	  Map<String, User> userMap = new HashMap<String,User>();
	  userMap.put("user1", user1);
	  userMap.put("user2", user2);
	  
	  GsonBuilder builder = new GsonBuilder();
	  Gson gson = builder.create();
	  String sUserMap = gson.toJson(userMap, new TypeToken<Map<String,User>>(){}.getType());
	  System.out.println(sUserMap);
	  
	  //创建Type,Type属于java.lang.reflect.Type
	  //Type type = new TypeToken<Map<String, User>>(){}.getType();
	 
	  Map<String,User> userMap2 = gson.fromJson(sUserMap, new TypeToken<Map<String, User>>() {}.getType());
	  System.out.println(userMap2.get("user1").getName());
}
}



你可能感兴趣的:(java,json,Google)