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);
}
}
您可以将其用作:
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);
}
}
以上代码打印:
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)
1条答案
按热度按时间8wigbo561#
您需要实现并注册自定义类型适配器:
您可以将其用作:
以上代码打印: