现在的位置: 首页 > 综合 > 正文

Gson简易使用小结

2017年02月18日 ⁄ 综合 ⁄ 共 3323字 ⁄ 字号 评论关闭

Gson是google提供的Json解析工具包,提供Json和Java对象之间的转化功能,效率较其他解析工具要快一些。

以下列出Json格式分别与数组、集合、对象间互相转换的sample。

代码如下:

package com.felix.gson;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

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

/**
 * Gson的使用小结: Array--Json、List--Json、Map--Json、Object--Json
 * 
 * @author JiHongfei
 */
public class Main {

	private static Gson g;
	private static int type = 3;//define by yourself

	private final static int ARRAY = 0;
	private final static int LIST = 1;
	private final static int MAP = 2;
	private final static int OBJECT = 3;

	public static void main(String[] args) {
		g = new Gson();

		switch (type) {
		case ARRAY:
			testArray();
			break;
		case LIST:
			testList();
			break;
		case MAP:
			testMAP();
			break;
		case OBJECT:
			testOBJECT();
			break;
		}
	}

	/**
	 * 对象与Json格式间转换
	 */
	private static void testOBJECT() {
		Person person = new Person("小龙女", "古墓", 18);
		String jsonString = g.toJson(person);
		System.out.println("jsonString of Person is: " + jsonString);
		
		Person fromJson = g.fromJson(jsonString, Person.class);
		System.out.println("Person of jsonString is: " + fromJson);
	}

	private static class Person {
		public Person(String name, String address, int age) {
			super();
			this.name = name;
			this.address = address;
			this.age = age;
		}

		public String name;
		public String address;
		public int age;
		@Override
		public String toString() {
			return "Person [name=" + name + ", address=" + address + ", age="
					+ age + "]";
		}
		
	}

	/**
	 * Map集合与Json格式间转换
	 */
	private static void testMAP() {
		Map<String, Integer> map = new HashMap<String, Integer>();// 存入是无序的,因此不一定按照put的顺序遍历出来
		map.put("张三", 20);
		map.put("李四", 22);
		map.put("王五", 24);
		String jsonString = g.toJson(map);
		System.out.println("jsonString of map is: " + jsonString);

		Type type = new TypeToken<HashMap<String, Integer>>() {
		}.getType();
		Map<String, Integer> fromJson = g.fromJson(jsonString, type);
		Set<Entry<String, Integer>> entrySet = fromJson.entrySet();
		for (Entry<String, Integer> entry : entrySet) {
			System.out.println("the key of map is: " + entry.getKey());
		}
	}

	/**
	 * List集合与Json格式间转换
	 */
	private static void testList() {
		ArrayList<String> list = new ArrayList<String>();
		list.add("淘宝");
		list.add("京东");
		list.add("亚马逊");
		String jsonString = g.toJson(list);
		System.out.println("jsonString of list is: " + jsonString);

		// TypeToken的使用,获得带泛型信息的type
		Type type = new TypeToken<ArrayList<String>>() {
		}.getType();
		ArrayList<String> fromJson = g.fromJson(jsonString, type);
		for (int i = 0; i < list.size(); i++) {
			System.out.println("element" + i + " of list is: "
					+ fromJson.get(i));
		}
	}

	/**
	 * 数组与Json格式间转换
	 */
	private static void testArray() {
		String arr[] = new String[] { "Monday", "Tuesday", "Friday" };
		String jsonString = g.toJson(arr);
		System.out.println("jsonString of arr[] is: " + jsonString);

		String[] fromJson = (String[]) g.fromJson(jsonString, String[].class);
		for (int i = 0; i < fromJson.length; i++) {
			System.out.println("arr[" + i + "] is: " + fromJson[i]);
		}
	}

}<strong>
</strong>

对象与Json格式间转换结果

jsonString of Person is: {"name":"小龙女","address":"古墓","age":18}
Person of jsonString is: Person [name=小龙女, address=古墓, age=18]

Map集合与Json格式间转换结果

jsonString of map is: {"李四":22,"张三":20,"王五":24}
the key of map is: 李四
the key of map is: 张三
the key of map is: 王五


List集合与Json格式间转换结果

jsonString of list is: ["淘宝","京东","亚马逊"]
element0 of list is: 淘宝
element1 of list is: 京东
element2 of list is: 亚马逊


数组与Json格式间转换结果

jsonString of arr[] is: ["Monday","Tuesday","Friday"]
arr[0] is: Monday
arr[1] is: Tuesday
arr[2] is: Friday

注意

由于Java泛型的实现机制,使用了泛型的代码在运行期间相关的泛型参数的类型会被擦除,我们无法在运行期间获知泛型参数的具体类型(所有的泛型类型在运行时都是Object类型)。因此借助了TypeToken获得携带泛型的类型。

详见 :“Gson通过借助TypeToken获取泛型参数的类型的方法”  http://www.blogjava.net/brock/archive/2012/08/01/384520.html

抱歉!评论已关闭.