Java Json objectToJsonDateSerializer(Object ts, final String dateformat)

Here you can find the source of objectToJsonDateSerializer(Object ts, final String dateformat)

Description

object To Json Date Serializer

License

Apache License

Declaration

public static String objectToJsonDateSerializer(Object ts, 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 {
    private static Gson gson = null;

    public static String objectToJsonDateSerializer(Object ts, final String dateformat) {
        String jsonStr = null;//from w ww .  j  a  v  a2s  . c  o m
        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(ts);
        }
        return jsonStr;
    }
}

Related

  1. jsonValueToJsonString(final JsonValue jsonValue, final String key)
  2. listToJsonArray(List list)
  3. mapToJsonObjectBuilder(Map map)
  4. newObject()
  5. nullable(String value)
  6. printJavaxJsonProvider()
  7. read(String jsonString)
  8. readMandatoryDateField(JsonParser jsonParser, String fieldName)
  9. requiredParams(JsonObject map, String... params)