Java Json to Object jsonToBeanDateSerializer(String jsonStr, Class cl, final String pattern)

Here you can find the source of jsonToBeanDateSerializer(String jsonStr, Class cl, final String pattern)

Description

json To Bean Date Serializer

License

Apache License

Declaration

public static <T> T jsonToBeanDateSerializer(String jsonStr, Class<T> cl, final String pattern) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    private static Gson gson = null;

    public static <T> T jsonToBeanDateSerializer(String jsonStr, Class<T> cl, final String pattern) {
        Object obj = null;/*from   w w w  .  jav a2  s .co  m*/
        gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {
                SimpleDateFormat format = new SimpleDateFormat(pattern);
                String dateString = json.getAsString();
                try {
                    return format.parse(dateString);
                } catch (Exception e) {

                }
                return null;
            }
        }).setDateFormat(pattern).create();

        if (gson != null) {
            obj = gson.fromJson(jsonStr, cl);
        }
        return (T) obj;
    }
}

Related

  1. json2List(String json, Class beanClass)
  2. json2map(String jsonStr)
  3. json2pojo(String jsonStr, Class clazz)
  4. jsonBigDecimal(JsonValue value)
  5. jsonStringToList(String jsonArrStr, Class clazz)
  6. jsonToList(String json, Class parametrized, Class... parameterClasses)
  7. jsonToList(String jsonStr, TypeReference valueTypeRef)
  8. jsonToMap(String src)
  9. jsonToObj(String json, Class clazz)