1

I have some JSON string snippets which could look like this:

{label: "My Label"}

{maxlength: 5}

{contact: {name: "John", "age": 5, children: [{"name": "Mary"]}}

etc, i.e. it could be any JSON object with any key names or value types.

Right now I am deserializing doing something pretty simple like this:

final Gson gson = new Gson();
Object newValue = gson.fromJson(stringValue, Object.class);

And this is working for 99% of the use cases. But as is mentioned here, it is converting any integers to doubles.

I'm fine registering a type adapter as is recommended elsewhere. So I wrote the following:

final Gson gson = new GsonBuilder()
                        .registerTypeAdapter(Object.class, new DoubleToInt())
                        .create();
Object newValue = gson.fromJson(stringValue, Object.class);

private static class DoubleToInt implements JsonDeserializer<Object>{

    @Override  
    public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

        // do my custom stuff here

        return json;
    }
}

But this isn't working at all. It's like the type adapter is not even getting registered because breakpoints never even hit in the deserialize method.

citizen conn
  • 15,300
  • 3
  • 58
  • 80

2 Answers2

1

In the post you linked, they suggested using a custom class in order to tell what data types you should use instead of using Object.class. Have you tried doing that?

    class CustomClass{
      String label;
      int maxLength;
      ...
    }

    Object newValue = gson.fromJson(stringValue, CustomClass.class);
Justin
  • 1,356
  • 2
  • 9
  • 16
1

As the post you link suggested, you should create custom class, so I did and it's working correctly:

public class Test {
    public static void main(String[] args) {
        final Gson gson = new GsonBuilder()
            .registerTypeAdapter(MyClass.class, new DoubleToInt())
            .create();
        String stringValue = "{contact: {name: \"John\", \"age\": 5, children: [{\"name\": \"Mary\"}]}}";

        MyClass newValue = gson.fromJson(stringValue, MyClass.class);
        System.out.println(newValue.toString());
    }

    private static class DoubleToInt implements JsonDeserializer<MyClass> {

        @Override
        public MyClass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

            // do my custom stuff here

            return new MyClass(json);
        }
    }
}

class MyClass {
    private JsonElement element;

    MyClass(JsonElement element) {
        this.element = element;
    }

    @Override
    public String toString() {
        return element.toString();
    }
}
Mohsen
  • 4,536
  • 2
  • 27
  • 49