`

Gson简单使用

    博客分类:
  • java
 
阅读更多

1.简单的处理list和map

Java代码
Gson gson = new Gson();   
List testList = new ArrayList();   
testList.add("first");   
testList.add("second");   
String listToJson = gson.toJson(testList);   
System.out.println(listToJson);        
//prints ["first","second"]   
  
Map testMap = new HashMap();   
testMap.put("id", "id.first");   
testMap.put("name","name.second");   
String mapToJson = gson.toJson(testMap);   
System.out.println(mapToJson);     
//prints {"id":"id.first","name":"name.second"}  
Gson gson = new Gson();
List testList = new ArrayList();
testList.add("first");
testList.add("second");
String listToJson = gson.toJson(testList);
System.out.println(listToJson);
//prints ["first","second"]
Map testMap = new HashMap();
testMap.put("id", "id.first");
testMap.put("name","name.second");
String mapToJson = gson.toJson(testMap);
System.out.println(mapToJson);
//prints {"id":"id.first","name":"name.second"} 2.处理带泛型的集合

Java代码
List<TestBean> testBeanList = new ArrayList<TestBean>();   
TestBean testBean = new TestBean();   
testBean.setId("id");   
testBean.setName("name");   
testBeanList.add(testBean);   
List<TestBean> testBeanList = new ArrayList<TestBean>();
TestBean testBean = new TestBean();
testBean.setId("id");
testBean.setName("name");
testBeanList.add(testBean);
Java代码
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<TestBean>>() {   
}.getType();   
String beanListToJson = gson.toJson(testBeanList,type);   
System.out.println(beanListToJson);   
//prints [{"id":"id","name":"name"}]   
  
List<TestBean> testBeanListFromJson = gson.fromJson(beanListToJson, type);   
System.out.println(testBeanListFromJson);   
//prints [TestBean@1ea5671[id=id,name=name,birthday=<null>]]  
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<TestBean>>() {
}.getType();
String beanListToJson = gson.toJson(testBeanList,type);
System.out.println(beanListToJson);
//prints [{"id":"id","name":"name"}]
List<TestBean> testBeanListFromJson = gson.fromJson(beanListToJson, type);
System.out.println(testBeanListFromJson);
//prints [TestBean@1ea5671[id=id,name=name,birthday=<null>]]map等其他集合类型同上





3.Date类型转化



先写工具类



Java代码
import java.lang.reflect.Type;   
  
import com.google.gson.JsonDeserializationContext;   
import com.google.gson.JsonDeserializer;   
import com.google.gson.JsonElement;   
import com.google.gson.JsonParseException;   
  
public class UtilDateDeserializer implements JsonDeserializer<java.util.Date> {   
  
    @Override  
    public java.util.Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)   
            throws JsonParseException {   
        return new java.util.Date(json.getAsJsonPrimitive().getAsLong());   
    }   
}  
import java.lang.reflect.Type;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class UtilDateDeserializer implements JsonDeserializer<java.util.Date> {
@Override
public java.util.Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return new java.util.Date(json.getAsJsonPrimitive().getAsLong());
}
}

Java代码
import java.lang.reflect.Type;   
  
import com.google.gson.JsonElement;   
import com.google.gson.JsonPrimitive;   
import com.google.gson.JsonSerializationContext;   
import com.google.gson.JsonSerializer;   
  
public class UtilDateSerializer implements JsonSerializer<java.util.Date> {   
  
    @Override  
    public JsonElement serialize(java.util.Date src, Type typeOfSrc,      
            JsonSerializationContext context) {      
        return new JsonPrimitive(src.getTime());      
    }      
  
}  
import java.lang.reflect.Type;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class UtilDateSerializer implements JsonSerializer<java.util.Date> {
@Override
public JsonElement serialize(java.util.Date src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(src.getTime());
}
}

Java代码
/**  
     * 序列化方法  
     * @param bean  
     * @param type  
     * @return  
     */  
    public static String bean2json(Object bean, Type type) {   
        Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.class, new UtilDateSerializer())   
                .setDateFormat(DateFormat.LONG).create();   
        return gson.toJson(bean);   
    }   
  
    /**  
     * 反序列化方法  
     * @param json  
     * @param type  
     * @return  
     */  
    public static <T> T json2bean(String json, Type type) {   
        Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.class, new UtilDateDeserializer())   
                .setDateFormat(DateFormat.LONG).create();   
        return gson.fromJson(json, type);   
    }  
/**
* 序列化方法
* @param bean
* @param type
* @return
*/
public static String bean2json(Object bean, Type type) {
Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.class, new UtilDateSerializer())
.setDateFormat(DateFormat.LONG).create();
return gson.toJson(bean);
}
/**
* 反序列化方法
* @param json
* @param type
* @return
*/
public static <T> T json2bean(String json, Type type) {
Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.class, new UtilDateDeserializer())
.setDateFormat(DateFormat.LONG).create();
return gson.fromJson(json, type);
}



现在开始测试



Java代码
List<TestBean> testBeanList = new ArrayList<TestBean>();   
TestBean testBean = new TestBean();   
testBean.setId("id");   
testBean.setName("name");   
testBean.setBirthday(new java.util.Date());   
testBeanList.add(testBean);   
  
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<TestBean>>() {   
}.getType();   
String beanListToJson = bean2json(testBeanList, type);   
System.out.println("beanListToJson:" + beanListToJson);   
//prints [{"id":"id","name":"name","birthday":1256531559390}]   
  
List<TestBean> testBeanListFromJson = json2bean(beanListToJson, type);   
System.out.println(testBeanListFromJson);   
//prints [TestBean@77a7f9[id=id,name=name,birthday=Mon Oct 26 12:39:05 CST 2009]]  
List<TestBean> testBeanList = new ArrayList<TestBean>();
TestBean testBean = new TestBean();
testBean.setId("id");
testBean.setName("name");
testBean.setBirthday(new java.util.Date());
testBeanList.add(testBean);
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<TestBean>>() {
}.getType();
String beanListToJson = bean2json(testBeanList, type);
System.out.println("beanListToJson:" + beanListToJson);
//prints [{"id":"id","name":"name","birthday":1256531559390}]
List<TestBean> testBeanListFromJson = json2bean(beanListToJson, type);
System.out.println(testBeanListFromJson);
//prints [TestBean@77a7f9[id=id,name=name,birthday=Mon Oct 26 12:39:05 CST 2009]]



后记:对于java.sql.Date的转化同上类似,写两个类用于其序列化和反序列化即可SQLDateDeserializer implements JsonDeserializer<java.sql.Date>

SQLDateSerializer implements JsonSerializer<java.sql.Date>

分享到:
评论

相关推荐

    非常详细的gson使用方法

    要将这个用户对象转换为JSON字符串,可以使用Gson的`toJson()`方法: ```java Gson gson = new Gson(); String jsonString = gson.toJson(user); ``` `jsonString`现在包含了User对象的JSON表示。 2. JSON字符串转...

    Gson基本使用方法

    ### Gson的基本使用方法 1. **添加依赖** 在项目中使用Gson,首先需要将其依赖引入到项目中。如果你使用的是Maven项目,可以在pom.xml文件中添加以下依赖: ```xml &lt;groupId&gt;com.google.code.gson&lt;/groupId&gt; ...

    Gson简要使用笔记

    Gson 库的强大之处在于其灵活性和简洁性,使得 JSON 序列化和反序列化变得更加简单。 首先,让我们深入了解一下 Gson 如何序列化 Java 对象。在提供的示例中,`Person` 类包含两个属性:`name`(String 类型)和 `...

    使用gson解析json

    本篇文章将深入探讨如何使用Gson库解析JSON。 一、Gson简介 Gson是Google提供的一个开源项目,它能够将Java对象转换成JSON格式的字符串,同时也可以将JSON数据转换回Java对象。这种转换过程非常方便,大大简化了...

    Android Gson使用Demo

    在这个“Android Gson使用Demo”中,我们将深入探讨如何在Android应用中有效利用Gson库。 首先,我们需要理解JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器...

    Gson解析复杂Json实例,超简单

    本教程将深入探讨如何使用Gson库解析复杂的JSON实例,让你只需寥寥几行代码就能轻松处理JSON解析问题。 ### Gson库简介 Gson库的核心功能是将Java对象(如自定义类)转换为JSON字符串,反之亦然。这个库非常直观,...

    Android Gson使用实例Demo

    这个"Android Gson使用实例Demo"旨在帮助开发者理解如何在Android应用中有效地使用Gson库来解析和生成JSON。 Gson的核心功能在于将Java对象转换为对应的JSON字符串,以及将JSON字符串反序列化为Java对象。在Android...

    gson jar包下载

    使用`Gson`类的`toJson()`方法,可以将Java对象转换为JSON字符串。例如,如果有一个`Person`类,你可以这样做: ```java Gson gson = new Gson(); Person person = new Person("John", "Doe"); String json...

    FastJson 和 Gson的使用简单方便

    Java处理JSON数据有三个比较流行的类库FastJSON、Gson和Jackson。本文将测试这三个类库在JSON序列化和反序列化的方面表现,主要测试JSON序列化和反序列化的速度。为了防止由于内存导致测试结果出现偏差,测试中对JVM...

    Gson项目使用

    Gson库的核心功能是将Java对象转换为它们对应的JSON字符串,反之亦然,使得JSON数据的处理变得简单而高效。 **一、Gson的基本用法** 1. **序列化(对象转JSON)** 当你需要将Java对象转换成JSON字符串时,可以...

    Gson简单与复杂json数据解析案例

    在"简单与复杂json数据解析案例"中,我们将探讨如何使用Gson处理各种JSON结构。 1. **Gson基本使用** - **序列化**: 将Java对象转换为JSON字符串。例如,有一个名为`Person`的类,包含`name`和`age`字段,我们可以...

    com.google.gson.Gson 2.8.1 2.8.2 jar包 gson

    Gson是Google开发的一款强大的Java库,用于在Java对象和JSON数据之间进行映射。...无论是简单的对象转换还是复杂的序列化需求,Gson都能够满足。而2.8.1和2.8.2版本的发布,更是对这个强大库的进一步完善和增强。

    Eclipse下使用Google Gson解析Json数据示例+Android Studio下使用Google Gson解析Json数据示例

    本文将详细介绍如何在Eclipse和Android Studio环境下使用Gson库来解析Json数据。 首先,我们来看Eclipse下的Gson使用示例。在Eclipse中,你需要先引入Gson库。这可以通过在项目构建路径中添加Gson的jar文件完成,...

    Gson的基本使用

    它的全称为Google Simple JSON,主要用于处理JSON格式的数据,特别是在Android开发中,Gson因其简单易用和高效的特点,被广泛应用于数据的序列化和反序列化。 ### Gson的主要特点 1. **快速、高效**:Gson的性能...

    Eclipse下使用Google Gson解析Json数据示例

    本教程将详细阐述如何在Eclipse环境中使用Gson来解析JSON数据。 首先,我们需要理解JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它基于ECMAScript的一个子集,采用完全独立于语言的文本格式,...

    Gson的三个jar包

    Gson库提供了简单易用的API,使得这些操作变得非常方便。下面我们将详细探讨Gson的主要功能和使用方法。 1. **序列化(对象转JSON)**:Gson允许我们将Java对象转换为JSON字符串。例如,如果你有一个User类,你可以...

    java中使用JSON的使用依赖包gson.jar

    本篇文章将深入探讨如何在Java项目中使用Gson.jar来处理JSON数据。 首先,我们需要了解Gson库的核心功能。Gson提供了一种简单的方法将Java对象转换为它们对应的JSON表示形式,以及将JSON字符串转换回相应的Java对象...

    使用Gson解析json数据

    本教程将重点介绍如何使用Gson库在Java环境中解析JSON数据。 Gson是Google提供的一款开源库,它能够将Java对象转换为对应的JSON字符串,也可以将JSON数据反序列化为Java对象。这对于处理JSON数据非常方便。在本示例...

Global site tag (gtag.js) - Google Analytics