0

I want to use Generic because I want it to suit many situations I encountered,so I used generic and didn't want to change, and here's my code as follows.

    /**
 * set json to map object
 *
 * @param jsonStr
 * @return
 */
public static Map<?, ?> jsonToMap(String jsonStr) {
    Map<?, ?> objMap = null;
    Gson gs = new GsonBuilder()
            .registerTypeAdapter(Double.class,  new JsonSerializer<Double>() {

                @Override
                public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
                    if (src == src.longValue())
                        return new JsonPrimitive(src.longValue());
                    return new JsonPrimitive(src);
                }

            }).create();
    if (gson != null) {
        java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<Map<?, ?>>() {
        }.getType();

        objMap = gson.fromJson(jsonStr, type);

    }
    return objMap;
}

The input is:

{id=1, level=2, name=Tom, gender=1} {id=3, level=4, name=Anny, gender=2}

The output is not what I want:

{id=1.0, level=2.0, name=Tom, gender=1.0} {id=3.0, level=4.0, name=Anny, gender=2.0}

Is there a way to have Integers instead of Doubles in my Map?

{id=1, level=2, name=Tom, gender=1} {id=3, level=4, name=Anny, gender=2}

ray
  • 13
  • 1
  • 5
  • You're using the Double class. Try it with the `Integer` class. – ifly6 Apr 30 '16 at 04:02
  • It seems that you want to customize the **deserialization** process (json to map). But the only thing you're doing here is to add a custom Json **Serializer**. – JB Nizet Apr 30 '16 at 07:11

0 Answers0