Java Json Create object2JsonDateSerializer(Object obj, final String dateformat)

Here you can find the source of object2JsonDateSerializer(Object obj, final String dateformat)

Description

object Json Date Serializer

License

Apache License

Declaration

public static String object2JsonDateSerializer(Object obj, final String dateformat) 

Method Source Code


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

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

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

import com.google.gson.JsonElement;

import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class Main {

    public static String object2JsonDateSerializer(Object obj, final String dateformat) {
        String jsonStr = null;/*from   w w  w .  ja va  2s .  com*/
        Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Date.class, new JsonSerializer<Date>() {
            public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
                SimpleDateFormat format = new SimpleDateFormat(dateformat);
                return new JsonPrimitive(format.format(src));
            }
        }).setDateFormat(dateformat).create();
        if (gson != null) {
            jsonStr = gson.toJson(obj);
        }
        return jsonStr;
    }
}

Related

  1. createJsonFrom(JsonObject user, String... ignoreKeys)
  2. createJsonValue(String string)
  3. createPrettyWriterFactory()
  4. emptyArray()
  5. getJson(T t)
  6. toBean(Class clazz, String json)
  7. toJson(E e)
  8. toJSON(Map map)
  9. toJson(Object object)