19.2. com.google.gson

简介:
		
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>sender</groupId>
	<artifactId>sender</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Sender</name>
	<description>EDM</description>

	<dependencies>
		<dependency>
			<groupId>com.rabbitmq</groupId>
			<artifactId>amqp-client</artifactId>
			<version>3.6.0</version>
		</dependency>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.6.2</version>
			<scope>compile</scope>
		</dependency>
	</dependencies>

</project>		
		
		

19.2.1. map 处理

Example

			
package io.github.netkiller;

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

import com.google.gson.*;

public class GsonTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Gson gson = new Gson();
		String json = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
		Map<String, String> map = new HashMap<String, String>();
		map = (Map<String, String>) gson.fromJson(json, map.getClass());
		System.out.println(map.get("k1"));
	}

}
			
			

多层 Map 剥离

			
		Gson gson = new Gson();
		String inf= "{\"0\":{\"id\":\"2\",\"category_id\":\"1\",\"title\":\"Test2\",\"author\":\"\",\"ctime\":\"2016-03-05 11:59:56\"},\"1\":{\"id\":\"1\",\"category_id\":\"1\",\"title\":\"Test1\",\"author\":\"\u6d4b\u8bd5\",\"ctime\":\"2016-03-05 11:57:30\"},\"pages\":{\"count\":2,\"first\":0,\"last\":0,\"before\":0,\"current\":0,\"next\":0,\"total\":0}}";
		Map<String, Map> map = new HashMap<String, Map>();
		
		map = (Map<String, Map>) gson.fromJson(inf, map.getClass());
		System.out.println(map.get("1").get("title"));
		System.out.println(map.get("pages").get("count"));
			
			

19.2.2. POJO

			
package cn.netkiller.gson;

import java.util.ArrayList;
import java.util.List;

public class Personal {
	private int age = 30;
	private String name = "neo";
	private List<String> telphone = new ArrayList<String>() {
		{
			add("13113668890");
			add("13322993040");
			add("29812080");
		}
	};

	// getter and setter methods

	@Override
	public String toString() {
		return "Personal [age=" + age + ", name=" + name + ", telphone=" + telphone + "]";
	}
}
			
			

19.2.3. toJson

			
package cn.netkiller.gson;

import com.google.gson.Gson;

public class GsonExampleToJson {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Personal obj = new Personal();
		Gson gson = new Gson();

		// convert java object to JSON format, and returned as JSON formatted string
		String json = gson.toJson(obj);
		System.out.println(json);
	}

}
			
			

19.2.4. fromJson

			
package cn.netkiller.gson;

import com.google.gson.Gson;

public class GsonExampleFromJson {
	public static void main(String[] args) {

		Personal obj = new Personal();
		Gson gson = new Gson();

		// convert the json string back to object
		obj = gson.fromJson("{\"age\":30,\"name\":\"neo\",\"telphone\":[\"13113668890\",\"13322993040\",\"29812080\"]}", Personal.class);

		System.out.println(obj);
	}
}
			
			

19.2.5. JsonParser

			
package cn.netkiller.gson;

import java.util.Map.Entry;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;

public class GsonJsonParser {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String jsonString = "{\"age\":30,\"name\":\"neo\",\"telphone\":[\"13113668890\",\"13322993040\",\"29812080\"],\"address\":{\"province\":\"Guangdong\",\"city\":\"Shenzhen\"}}";

		JsonElement root = new JsonParser().parse(jsonString);
		System.out.println(root.toString());
		System.out.println(root.getAsJsonObject().get("age").getAsInt());
		System.out.println(root.getAsJsonObject().get("name").getAsString());

		// Get the content of the first map
		JsonArray jsonArray = root.getAsJsonObject().get("telphone").getAsJsonArray();

		for (JsonElement tel : jsonArray) {
			System.out.println(tel);
		}

		JsonObject object = root.getAsJsonObject().get("address").getAsJsonObject();
		for (Entry<String, JsonElement> entry : object.entrySet()) {
			System.out.println(entry.getKey() + ":" + entry.getValue());
		}
	}

}
			
			

19.2.6. Exmaple 范例

19.2.6.1. Map to Json

				
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
String jsonString = gson.toJson(map);
				
				

19.2.7. Exmaple 范例

19.2.7.1. Map to Json

				
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
Map<String, String> source = gson.fromJson(output, HashMap.class);
				
				

19.2.8. 处理复杂的类型

通过 TypeToken 定义复杂数据库类型。

			
package cn.netkiller.ipo.process.json;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import cn.netkiller.ipo.process.ProcessInterface;

public class JsonValueLength implements ProcessInterface {
	private final static Logger logger = LoggerFactory.getLogger(JsonValueLength.class);
	private Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
	private int maxLength = 0;

	public JsonValueLength(int maxLength) {
		this.maxLength = maxLength;
	}

	@Override
	public String run(String line) {

		Map<String, String> map = gson.fromJson(line, new TypeToken<Map<String, String>>() {
		}.getType());
		for (String key : map.keySet()) {
			if (map.get(key).length() > this.maxLength) {
				map.put(key, map.get(key).substring(0, this.maxLength));
			}
		}
		logger.debug("{}", map);
		return gson.toJson(map);
	}

}

			
			




原文出处:Netkiller 系列 手札
本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。

目录
相关文章
|
JSON fastjson Java
FastJson、JackJson 以及 Gson 的区别
FastJson、JackJson 以及 Gson 是 Java 生态圈中三种常用的 Json 解析器,它们均可将 Java 对象序列化为 Json 格式的字符串,也可将 Json 字符串反序列化为 Java 对象。下面我们讨论一下三者在序列化和反序列化操作中的一些区别。
845 0
|
11天前
|
JSON fastjson Java
Gson与FastJson详解
综上,Gson和FastJson都是用于Java对象和JSON数据互相转换的优秀库,选择哪个取决于性能、功能需求和个人偏好。 买CN2云服务器,免备案服务器,高防服务器,就选蓝易云。百度搜索:蓝易云
23 2
|
1月前
|
缓存 安全 Java
Google guava工具类的介绍和使用
Google guava工具类的介绍和使用
37 1
|
5月前
|
JSON 数据格式
gson坑
gson坑
33 0
|
10月前
|
JSON 安全 fastjson
gson与fastjson
gson与fastjson
94 0
|
11月前
|
JSON Java API
Gson-更新中
Gson-更新中
125 0
|
JSON Android开发 数据格式
android studio中出现com.google.gson.JsonSyntaxException: com.google.gson.stream.类似错误的一种解决方案
android studio中出现com.google.gson.JsonSyntaxException: com.google.gson.stream.类似错误的一种解决方案
212 0
android studio中出现com.google.gson.JsonSyntaxException: com.google.gson.stream.类似错误的一种解决方案
|
API
Google Guava之Joiner
日常开发中,我们经常需要将几个字符串,或者字符串数组、列表之类的数据,拼接成一个以指定符号分隔各个元素的字符串,比如把[1, 2, 3]拼接成"1-2-3",如果自己实现的话,基本上就需要编写循环去实现这个功能,代码就变得晦涩起来。
175 0
Google Guava之Joiner
|
JSON 数据格式
GSON - 基础篇
GSON - 基础篇
169 0
|
JSON 数据可视化 fastjson
Gson 简单使用姿势小结
关于 Json 序列化的框架可以说比较多了,比如 Spring 默认的 Jackson,国内互联网用的比较多的 FastJson,本文则主要介绍一下 Gson 的简单使用姿势,并不会涉及到不同的 json 框架的性能对比
181 0
Gson 简单使用姿势小结