Java Json to Object jsonToObject(String jsonString, Class classOfT)

Here you can find the source of jsonToObject(String jsonString, Class classOfT)

Description

json To Object

License

Open Source License

Declaration

public static <T> T jsonToObject(String jsonString, Class<T> classOfT) 

Method Source Code


//package com.java2s;
//License from project: Open Source 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;
import com.google.gson.internal.Primitives;

public class Main {
    final static String dateformat = "yyyy-MM-dd'T'hh:ss:mm";

    public static <T> T jsonToObject(String jsonString, Class<T> classOfT) {
        //      Gson gson = new Gson();
        Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Date.class, new JsonSerializer<Date>() {
            @Override//from   w w w  .j ava 2  s . co m
            public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
                SimpleDateFormat format = new SimpleDateFormat(dateformat);
                return new JsonPrimitive(format.format(src));
            }
        }).setDateFormat(dateformat).create();

        Object object = gson.fromJson(jsonString, (Type) classOfT);
        return Primitives.wrap(classOfT).cast(object);
    }
}

Related

  1. jsonToList(String jsonStr, TypeReference valueTypeRef)
  2. jsonToMap(String src)
  3. jsonToObj(String json, Class clazz)
  4. jsonToObj(String json, Class valueType)
  5. jsonToObject(String json, Class toValueType)
  6. jsonToPojo(String jsonData, Class beanType)
  7. parse(String jsonLine)
  8. readValue(String jsonStr, Class valueType)
  9. stringForJSON(String input)