Example usage for com.google.gson JsonDeserializer JsonDeserializer

List of usage examples for com.google.gson JsonDeserializer JsonDeserializer

Introduction

In this page you can find the example usage for com.google.gson JsonDeserializer JsonDeserializer.

Prototype

JsonDeserializer

Source Link

Usage

From source file:com.android.tools.idea.stats.DistributionService.java

License:Apache License

@Nullable
private static List<Distribution> loadDistributionsFromJson(String jsonString) {
    Type fullRevisionType = new TypeToken<Revision>() {
    }.getType();//from  www  .  ja v  a 2  s  .  co m
    GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(fullRevisionType,
            new JsonDeserializer<Revision>() {
                @Override
                public Revision deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                        throws JsonParseException {
                    return Revision.parseRevision(json.getAsString());
                }
            });
    Gson gson = gsonBuilder.create();
    Type listType = new TypeToken<ArrayList<Distribution>>() {
    }.getType();
    try {
        return gson.fromJson(jsonString, listType);
    } catch (JsonParseException e) {
        LOG.error("Parse exception while reading distributions.json", e);
    }
    return null;
}

From source file:com.android.tools.idea.wizard.DistributionChartComponent.java

License:Apache License

@Nullable
private static List<Distribution> loadDistributionsFromJson(String jsonString) {
    Type fullRevisionType = new TypeToken<FullRevision>() {
    }.getType();//  w ww.ja  va2 s. c  om
    GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(fullRevisionType,
            new JsonDeserializer<FullRevision>() {
                @Override
                public FullRevision deserialize(JsonElement json, Type typeOfT,
                        JsonDeserializationContext context) throws JsonParseException {
                    return FullRevision.parseRevision(json.getAsString());
                }
            });
    Gson gson = gsonBuilder.create();
    Type listType = new TypeToken<ArrayList<Distribution>>() {
    }.getType();
    try {
        return gson.fromJson(jsonString, listType);
    } catch (JsonParseException e) {
        LOG.error(e);
    }
    return null;
}

From source file:com.arcbees.plugin.idea.wizards.createproject.FetchArchetypes.java

License:Apache License

private GsonBuilder createGsonBuilder() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }//ww  w.  j  a  v  a 2s  .c o m
    });
    gsonBuilder.registerTypeAdapter(ArchetypeCollection.class, new JsonDeserializer<ArchetypeCollection>() {
        public ArchetypeCollection deserialize(JsonElement json, Type typeOft,
                JsonDeserializationContext context) throws JsonParseException {
            JsonObject parentJson = json.getAsJsonObject();

            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                        throws JsonParseException {
                    return new Date(json.getAsJsonPrimitive().getAsLong());
                }
            });
            Gson gson = gsonBuilder.create();

            ArchetypeCollection parent = gson.fromJson(json, ArchetypeCollection.class);
            List<Archetype> archetypes = null;

            if (parentJson.get("items").isJsonArray()) {
                JsonElement itemsJson = parentJson.get("items");
                archetypes = gson.fromJson(itemsJson, new TypeToken<List<Archetype>>() {
                }.getType());
            } else {
                Archetype single = gson.fromJson(parentJson.get("items"), Archetype.class);
                archetypes = new ArrayList<Archetype>();
                archetypes.add(single);
            }
            parent.setArchetypes(archetypes);
            return parent;
        }
    });
    return gsonBuilder;
}

From source file:com.b12kab.tmdblibrary.TmdbHelper.java

License:Apache License

/**
 * Create a {@link com.google.gson.GsonBuilder} and register all of the custom types needed in
 * order to properly deserialize complex TMDb-specific types.
 *
 * @return Assembled GSON builder instance.
 *///from   w w w  . j a  v  a  2s . c  om
public static GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();

    // class types
    builder.registerTypeAdapter(AccountState.class, new AccountStateDeserializer());
    builder.registerTypeAdapter(Integer.class, new JsonDeserializer<Integer>() {
        @Override
        public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            try {
                return Integer.valueOf(json.getAsInt());
            } catch (NumberFormatException e) {
                return null;
            }
        }
    });
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {

            try {
                return JSON_STRING_DATE.parse(json.getAsString());
            } catch (ParseException e) {
                return null;
            }
        }
    });

    return builder;
}

From source file:com.balajeetm.mystique.util.gson.GsonFactory.java

License:Open Source License

/**
 * Gets the gson builder.//from www. j a v a 2  s  .  c  o  m
 *
 * @return the gson builder
 */
public GsonBuilder getGsonBuilder() {
    if (null == gsonBuilder) {
        gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat(DateFormat.LONG, DateFormat.LONG);
        gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {
                Date date = null;
                if (null != json && json.isJsonPrimitive()) {
                    date = new Date(json.getAsJsonPrimitive().getAsLong());
                }
                return date;
            }
        });
        gsonBuilder.registerTypeAdapter(XMLGregorianCalendar.class, new JsonSerializer<XMLGregorianCalendar>() {

            @Override
            public JsonElement serialize(XMLGregorianCalendar src, Type typeOfSrc,
                    JsonSerializationContext context) {
                Date date = null;
                if (null != src) {
                    date = src.toGregorianCalendar().getTime();
                }
                return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(date));
            }
        });
    }
    return gsonBuilder;
}

From source file:com.bing.maps.rest.services.impl.BaseBingMapsApiQuery.java

License:Apache License

/**
 * Gets the gson builder.// w ww  .  j a va  2 s  .  c  o m
 * 
 * @return the gson builder
 */
protected GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();
    builder.setDateFormat(ApplicationConstants.RFC822DATEFORMAT);
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    builder.registerTypeAdapter(LocationType.class, new JsonDeserializer<LocationType>() {
        @Override
        public LocationType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return LocationType.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(AddressComponentType.class, new JsonDeserializer<AddressComponentType>() {
        @Override
        public AddressComponentType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return AddressComponentType.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(TravelMode.class, new JsonDeserializer<TravelMode>() {
        @Override
        public TravelMode deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return TravelMode.fromValue(arg0.getAsString());
        }
    });

    return builder;
}

From source file:com.cloudant.client.org.lightcouch.internal.GsonHelper.java

License:Open Source License

/**
 * Builds {@link Gson} and registers any required serializer/deserializer.
 *
 * @return {@link Gson} instance/*from   w  w w.  j  a va2s .  com*/
 */
public static GsonBuilder initGson(GsonBuilder gsonBuilder) {
    gsonBuilder.registerTypeAdapter(JsonObject.class, new JsonDeserializer<JsonObject>() {
        public JsonObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return json.getAsJsonObject();
        }
    });
    gsonBuilder.registerTypeAdapter(JsonObject.class, new JsonSerializer<JsonObject>() {
        public JsonElement serialize(JsonObject src, Type typeOfSrc, JsonSerializationContext context) {
            return src.getAsJsonObject();
        }

    });

    return gsonBuilder;
}

From source file:com.code19.library.GsonUtil.java

License:Apache License

@SuppressWarnings("unchecked")
public static <T> T jsonToBeanDateSerializer(String jsonStr, Class<T> cl, final String pattern) {
    Object obj = null;/*  w w  w. java  2 s . c o m*/
    gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            SimpleDateFormat format = new SimpleDateFormat(pattern);
            String dateStr = json.getAsString();
            try {
                return format.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return null;
        }
    }).setDateFormat(pattern).create();
    if (gson != null) {
        obj = gson.fromJson(jsonStr, cl);
    }
    return (T) obj;
}

From source file:com.daon.identityx.samplefidoapp.RelyingPartyServerComms.java

License:Apache License

public RelyingPartyServerComms(Context context) {
    builder = new GsonBuilder();
    //        builder.registerTypeAdapter(Timestamp.class, new JsonDeserializer<Timestamp>() {
    //            public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    //                return new Timestamp(json.getAsJsonPrimitive().getAsLong());
    //            }
    //        });
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
            try {
                String dateAsString = json.getAsJsonPrimitive().getAsString().replaceAll("\"", "");
                return formatter.parse(dateAsString);
            } catch (Exception ex) {
                return new Date();
            }//from w  w w  .jav  a  2  s .c  om
        }
    });

    this.context = context;
}

From source file:com.dell.prototype.apm.server.AppServerMonitorDataSubmissionServlet.java

License:Open Source License

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
    String line = "";
    try {//from   w w w .j ava  2s  .c  om
        line = request.getReader().readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String[] msgs = line.split(";;");
    List<Request> requests = new ArrayList<Request>();

    Gson gson = new GsonBuilder()
            .registerTypeAdapter(RequestTiming.class, new JsonDeserializer<RequestTiming>() {
                @Override
                public RequestTiming deserialize(JsonElement jsonElement, Type type,
                        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
                    if (!jsonElement.isJsonObject())
                        return new RequestTiming();

                    String name = ((JsonObject) jsonElement).getAsJsonPrimitive("name").getAsString();
                    if ("database".equals(name)) {
                        DatabaseTiming databaseTiming = new DatabaseTiming(name);
                        databaseTiming
                                .setTime(((JsonObject) jsonElement).getAsJsonPrimitive("time").getAsLong());
                        String sql = ((JsonObject) jsonElement).getAsJsonPrimitive("sql").getAsString();
                        databaseTiming.setSql(sql);
                        List<String> bindingParameters = new ArrayList<String>();
                        for (JsonElement bindParameter : ((JsonObject) jsonElement).get("bindingParameters")
                                .getAsJsonArray()) {
                            bindingParameters.add(bindParameter.getAsString());
                        }
                        databaseTiming.setBindingParameters(bindingParameters);
                        return databaseTiming;
                    }
                    RequestTiming requestTiming = new RequestTiming();
                    requestTiming.setName("server");
                    requestTiming.setTime(((JsonObject) jsonElement).getAsJsonPrimitive("time").getAsLong());
                    return requestTiming;
                }
            }).create();
    for (int i = 0; i < msgs.length - 1; i++) {
        if (null != msgs[i] && !"".equals(msgs[i])) {
            requests.add(gson.fromJson(msgs[i], Request.class));
        }
    }
    String jvmMsg = msgs[msgs.length - 1];
    JVM jvm = gson.fromJson(jvmMsg, JVM.class);
    Metric<JVM> avgThreadCpuTime = jvm.getAvgThreadCpuTime();
    setParent(jvm, avgThreadCpuTime);

    Metric<JVM> committedHeap = jvm.getCommittedHeap();
    setParent(jvm, committedHeap);

    Metric<JVM> usedHeap = jvm.getUsedHeap();
    setParent(jvm, usedHeap);

    Metric<JVM> gcOverhead = jvm.getGcOverhead();
    setParent(jvm, gcOverhead);

    Metric<JVM> threadsCount = jvm.getThreadsCount();
    setParent(jvm, threadsCount);

    ApplicationServer server = APMPrototype.getRoot().getAppServer();
    server.setRequests(requests);
    if (server.getJvm() == null)
        server.creatJVM(jvm.getName(), jvm.getVersion(), jvm.getArchitecture());

    JVM storedJvm = server.getJvm();
    storedJvm.setName(jvm.getName());
    storedJvm.setArchitecture(jvm.getArchitecture());
    storedJvm.setVersion(jvm.getVersion());

    mergeJVM(jvm, storedJvm);
}