Gson. Deserialize integers as integers and not as doubles

后端 未结 7 1027
我寻月下人不归
我寻月下人不归 2020-12-09 16:46

I have json object with arbitary values inside. And I want to deserialize it in a Map. Everything is ok except converting integers to a doubles. See example:



        
7条回答
  •  囚心锁ツ
    2020-12-09 17:32

    Here is my example, the first part is the definition of the class that has an int type field.

    import com.google.api.client.util.Key;
    
    public class Folder {
    
        public static final String FIELD_NAME_CHILD_COUNT = "childCount";
    
        @Key(FIELD_NAME_CHILD_COUNT)
        public final int childCount;
    
        public Folder(int aChildCount) {
            childCount = aChildCount;
        }
    }
    

    Then the TypeAdapter to convert the number type in Gson to a Java object.

    GsonBuilder gsb = new GsonBuilder();
    
    gsb.registerTypeAdapter(Folder.class, new JsonDeserializer() {
    
                @Override
                public Folder deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    
                    int value = json.getAsJsonObject().get("childCount").getAsJsonPrimitive().getAsInt();
    
                    return new Folder(value);
    
                }
            }
    );
    

    The third part is the test data, and it works.

    String gsonData =  new String("\"folder\":{\"childCount\":0}");
    

提交回复
热议问题