Google Gson解析Json数据应用实例

1.需要的Jar包

    1) Google Gson(gson-xxx.jar)下载地址:http://code.google.com/p/google-gson/downloads/list

    2)JUnit4

2. 应用实例代码

    下载地址:http://download.csdn.net/source/3499627

包括如下类:

1)普通JavaBean类/带日期属性的JavaBean类:JavaBean.java/DateBean.java

2)日期序列/反序列工具类:DateSerializerUtils.java、DateDeserializerUtils.java

3)测试类GsonTester.java

具体代码:

1)JavaBean类/DateBean类

     JavaBean属性:String id、String name、int age、String addr;

     DateBean属性:String id、String name、int age、java.util.Date date;

2)

DateSerializerUtils.java

package com.lupeng.javase.json.util;

 

import java.lang.reflect.Type;

import java.util.Date;

import com.google.gson.JsonElement;

import com.google.gson.JsonPrimitive;

import com.google.gson.JsonSerializationContext;

import com.google.gson.JsonSerializer;

 

/**

 * 日期解序列实用工具类

 * @author Lupeng

 * @date   2011-08-06

 */

public class DateSerializerUtils implements JsonSerializer<java.util.Date>{

    @Override

    public JsonElement serialize(Date date, Type type,

           JsonSerializationContext content) {

       return new JsonPrimitive(date.getTime());

    }

 

}

DateDeserializerUtils.java

package com.lupeng.javase.json.util;

 

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;

/**

 * 日期序列化实用工具类

 * @author Lupeng

 * @date   2011-08-06

 */

public class DateDeserializerUtils implements JsonDeserializer<java.util.Date>{

    @Override

    public java.util.Date deserialize(JsonElement json, Type type,

           JsonDeserializationContext context) throws JsonParseException {

       return new java.util.Date(json.getAsJsonPrimitive().getAsLong());

    }

 

}

 

3)测试类GsonTester.java

package com.lupeng.javase.apps.json;

 

import java.text.DateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.junit.Before;

import org.junit.Test;

 

import com.google.gson.Gson;

import com.google.gson.GsonBuilder;

import com.lupeng.javase.json.bean.DateBean;

import com.lupeng.javase.json.bean.JavaBean;

import com.lupeng.javase.json.util.DateDeserializerUtils;

import com.lupeng.javase.json.util.DateSerializerUtils;

 

/**

 * Google Gson解析Json数据实例

 *

 * 1.BeanJson转换          testBeanJson()

 * 2.List -> Json转换     testList2Json()

 * 3.泛型ListJson相互转换 testGenericList2Json()

 * 4.Map -> Json转换         testMap2Json()

 * 5.泛型MapJson相互转换 testGenericMap2Json()

 * 6.带日期属性BeanJson转换  testDateBeanJson()

 * 7.带日期属性泛型ListJson转换

 *                           testDateGenericListJson()

 *

 * @author Lupeng

 * @create 2011-08-05

 * @modify 2011-08-06

 */

@SuppressWarnings("unchecked")

public class GsonTester {

    private Gson gson = null;

    private GsonBuilder gsonBuilder = null;

   

    @Before

    public void setUp() {

       gson = new Gson();

       gsonBuilder = new GsonBuilder();

    }

    /**

     * JavaBeanJson相互转换

     */

    @Test

    public void testBeanJson() {

       JavaBean bean = new JavaBean("1001""scott", 20, "TL");

      

       // Bean -> Json

       String json = gson.toJson(bean);

       System.out.println(json);

      

       // Json -> Bean

       bean = gson.fromJson(json, JavaBean.class);

       System.out.println(bean);

    }

   

    /**

     * List转换成Json字符串

     */

    @Test

    public void testList2Json() {

       // List

       List list = new ArrayList();

       for(int i = 0; i < 5; i++) {

           list.add("element" + i);

       }

       System.out.println(list);

      

       // List -> Json

       String json = gson.toJson(list);

       System.out.println(json);

    }

   

    /**

     * 泛型ListJson相互转换

     */

    @Test

    public void testGenericListJson() {

       // 泛型List

       List<JavaBean> list = new ArrayList<JavaBean>();

       for(int i = 0; i < 3; i++) {

           JavaBean user = new JavaBean("100" + i, "name" + i, 20 + i, "BJ" + i);

           list.add(user);

       }

       System.out.println(list);

      

       // 泛型List -> Json

       java.lang.reflect.Type type =

           new com.google.gson.reflect.TypeToken<List<JavaBean>>(){}.getType();

       String json = gson.toJson(list, type);

       System.out.println(json);  

      

       // Json -> 泛型List

       List<JavaBean> users = gson.fromJson(json.toString(), type);

       System.out.println(users);

    }

   

    /**

     * Map转换成Json字符串

     */

    @Test

    public void testMap2Json() {

       // Map数据

       Map map = new HashMap();

       map.put("id""1001");

       map.put("name""scott");

       map.put("age", 20);

       map.put("addr""BJ");

       System.out.println(map);

      

       // Map -> Json

       String json = gson.toJson(map);

       System.out.println(json);

    }

   

    /**

     * 泛型MapJson相互转换

     */

    @Test

    public void testGenericMapJson() {

       // 泛型Map数据

       Map<String, JavaBean> map = new HashMap<String, JavaBean>();

       for(int i = 0; i < 5; i++) {

           JavaBean user = new JavaBean("100" + i, "name" + i, 20 + i, "LN" + i);

           map.put("100" + i, user);

       }

       System.out.println(map);

      

       // 泛型Map -> Json

       java.lang.reflect.Type type =

           new com.google.gson.reflect.TypeToken<Map<String, JavaBean>>(){}.getType();

       String json = gson.toJson(map, type);

       System.out.println(json);  

      

       // Json -> Map

       Map<String, JavaBean> users = gson.fromJson(json.toString(), type);

       System.out.println(users);

      

    }

   

    /**

     * 带日期类型BeanJson相互转换

     */

    @Test

    public void testDateBeanJson() {

       // 日期Bean数据

       DateBean bean = new DateBean("1001""scott", 20, new Date());

      

       // Bean(带日期属性) -> Json

       gson = gsonBuilder.registerTypeAdapter(java.util.Date.class,

              new DateSerializerUtils()).setDateFormat(DateFormat.LONG).create();

       String json = gson.toJson(bean);

       System.out.println(json);

      

       // Json -> Bean(带日期类型属性)

       gson = gsonBuilder.registerTypeAdapter(java.util.Date.class,

              new DateDeserializerUtils()).setDateFormat(DateFormat.LONG).create();

       java.lang.reflect.Type type =

           new com.google.gson.reflect.TypeToken<DateBean>(){}.getType();

       DateBean b = gson.fromJson(json, type);

       System.out.println(b);

    }

    /**

     * 泛型日期ListJson相互转换

     */

    @Test

    public void testDateGenericListJson() {

       // 泛型日期List

       List<DateBean> list = new ArrayList<DateBean>();

       for(int i = 0; i < 3; i++) {

           DateBean user = new DateBean("100" + i, "name" + i, 20 + i, new Date());

           list.add(user);

       }

       System.out.println(list);

      

       // 泛型日期List -> Json

       gson = gsonBuilder.registerTypeAdapter(java.util.Date.class,

              new DateSerializerUtils()).setDateFormat(DateFormat.LONG).create();

       java.lang.reflect.Type type =

           new com.google.gson.reflect.TypeToken<List<DateBean>>(){}.getType();

       String json = gson.toJson(list, type);

       System.out.println(json);  

      

       // Json -> 泛型日期List

       gson = gsonBuilder.registerTypeAdapter(java.util.Date.class,

              new DateDeserializerUtils()).setDateFormat(DateFormat.LONG).create();

       List<DateBean> users = gson.fromJson(json.toString(), type);

       System.out.println(users);

    }

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
包含以下java源文件: com.google.gson.DefaultDateTypeAdapter.class com.google.gson.ExclusionStrategy.class com.google.gson.FieldAttributes.class com.google.gson.FieldNamingPolicy.class com.google.gson.FieldNamingStrategy.class com.google.gson.Gson.class com.google.gson.GsonBuilder.class com.google.gson.InstanceCreator.class com.google.gson.JsonArray.class com.google.gson.JsonDeserializationContext.class com.google.gson.JsonDeserializer.class com.google.gson.JsonElement.class com.google.gson.JsonIOException.class com.google.gson.JsonNull.class com.google.gson.JsonObject.class com.google.gson.JsonParseException.class com.google.gson.JsonParser.class com.google.gson.JsonPrimitive.class com.google.gson.JsonSerializationContext.class com.google.gson.JsonSerializer.class com.google.gson.JsonStreamParser.class com.google.gson.JsonSyntaxException.class com.google.gson.LongSerializationPolicy.class com.google.gson.TreeTypeAdapter.class com.google.gson.TypeAdapter.class com.google.gson.TypeAdapterFactory.class com.google.gson.annotations.Expose.class com.google.gson.annotations.SerializedName.class com.google.gson.annotations.Since.class com.google.gson.annotations.Until.class com.google.gson.internal.ConstructorConstructor.class com.google.gson.internal.Excluder.class com.google.gson.internal.JsonReaderInternalAccess.class com.google.gson.internal.LazilyParsedNumber.class com.google.gson.internal.LinkedTreeMap.class com.google.gson.internal.ObjectConstructor.class com.google.gson.internal.Primitives.class com.google.gson.internal.Streams.class com.google.gson.internal.UnsafeAllocator.class com.google.gson.internal.bind.ArrayTypeAdapter.class com.google.gson.internal.bind.CollectionTypeAdapterFactory.class com.google.gson.internal.bind.DateTypeAdapter.class com.google.gson.internal.bind.JsonTreeReader.class com.google.gson.internal.bind.JsonTreeWriter.class com.google.gson.internal.bind.MapTypeAdapterFactory.class com.google.gson.internal.bind.ObjectTypeAdapter.class com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.class com.google.gson.internal.bind.SqlDateTypeAdapter.class com.google.gson.internal.bind.TimeTypeAdapter.class com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.class com.google.gson.internal.bind.TypeAdapters.class com.google.gson.reflect.TypeToken.class com.google.gson.stream.JsonReader.class com.google.gson.stream.JsonScope.class com.google.gson.stream.JsonToken.class com.google.gson.stream.JsonWriter.class com.google.gson.stream.MalformedJsonException.class

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值