How disable Gson deserilization from Number to String

You need to implement and register custom type adapter:

class StrictStringTypeAdapter extends TypeAdapter<String> {
    @Override
    public String read(JsonReader in) throws IOException {
        JsonToken peek = in.peek();
        if (peek == JsonToken.NULL) {
            in.nextNull();
            return null;
        }

        if (peek != JsonToken.STRING) {
            throw new JsonParseException("Non-string token!");
        }
        return in.nextString();
    }

    @Override
    public void write(JsonWriter out, String value) throws IOException {
        out.value(value);
    }
}

And you can use it as:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

public class GsonApp {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(String.class, new StrictStringTypeAdapter())
                .create();
        X coordinates = gson.fromJson("{\"a\": 123, \"b\": 456}", X.class);
    }
}

Above code prints:

Exception in thread "main" com.google.gson.JsonParseException: Non-string token!
    at com.example.StrictStringTypeAdapter.read(GsonApp.java:33)
    at com.example.StrictStringTypeAdapter.read(GsonApp.java:23)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top