Prefacio
En proyectos de desarrollo reales, el servidor a menudo usa la cadena vacía "" como resultado de retorno para representar el valor vacío, pero esto encontrará problemas en GSON. Si el tipo de datos no es una cadena, GSON informará un error al analizarlo.
Excepción json
Primero veamos a un JSON devuelto en el fondo
En circunstancias normales JSON:
{"código": 0, "msg": "ok", "datos": {"id": 5638, "NewsId": 5638}}La clase de entidad correspondiente a la parte de datos:
clase pública jsonbean {private int id; Private int Newsid; public int getId () {return id; } public void setid (int id) {this.id = id; } public int getNewsid () {return NewsId; } public void setNewsid (int newsid) {this.newsid = NewsId; }}Excepción JSON (los datos correspondientes no se encuentran en el campo de la base de datos de antecedentes NewsID):
{"código": 0, "msg": "ok", "datos": {"id": 5638, "NewsId": ""}}De esta manera, Gson lanzará una excepción con errores de análisis al análisis, y la aplicación se bloquea porque no puede convertir "" en int
Manejo de excepciones JSON
Esperamos que cuando la excepción JSON devuelta en el fondo se pueda analizar con éxito, el valor nulo correspondiente se convierte en el valor predeterminado, como: newsId=0;
Aquí excluyamos las correcciones para usted cuando los desarrolladores de fondo producen, todavía tenemos que confiar en nosotros mismos,
Escribimos un convertidor de tipo para los valores int, que necesita implementar la interfaz JsonSerializer<T> de GSON y JsonDeserializer<T> , es decir, interfaces de serialización y deserialización
Public Class IntegerDefault0Adapter implementa JSonserializer <integer>, JSondeserializer <integer> {@Override public Integer Deserialize (jsonelement json, typeft, jSondeserializationContext context) tira jsonparseexception {intit {if (json.getAsstring (). Ecalios ("") | "") json.getAsstring (). Equals ("null")) {// Definir como tipo int type, si el fondo devuelve "" o nulo, return 0; }} catch (excepción ignore) {} try {return json.getAsInt (); } catch (numberFormateException e) {tire new JSonsyntaxException (e); }} @Override public JSONELEMENT SERIALIZE (Integer Src, type typeOfSrc, jSonserializationContext context) {return new JsonPrimitive (src); }} Del mismo modo, tipos largos y dobles
doble =>
La clase pública DoubleDefault0Adapter implementa JSonserializer <Souble>, JSondeserializer <Double> {@Override public Double Deserialize (JSONELEMENT JSON, Type TypeOft, JSondeserializationContext context) lanza JSONPARSEEXCECETION {Try {si (JSON.GetAstring (). json.getAsstring (). Equals ("null")) {// Definir como tipo doble, si el fondo devuelve "" o nulo, return 0.00 return 0.00; }} capt (excepción ignore) {} try {return json.getasdouble (); } catch (numberFormateException e) {tire new JSonsyntaxException (e); }} @Override public jSonElement Serialize (doble src, type typeOfSrc, jsonserializationContext context) {return new JsonPrimitive (SRC); }}largo =>
La clase pública LongDefault0Adapter implementa JSonserializer <Rong>, JSondeserializer <Long> {@Override public Long Deserialize (JSONELEMENT JSON, Type TypeOft, JSondeserializationContext context) lanza JSONPARSEEXCECETION {Try {si (JSON.GetAstring (). json.getAstring (). Equals ("null")) {// Definir como tipo largo, si el fondo devuelve "" o nulo, return 0l; }} catch (excepción ignore) {} try {return json.getAslong (); } catch (numberFormateException e) {tire new JSonsyntaxException (e); }} @Override public jSonElement Serialize (Long Src, type typeOfSrc, JSonSerializationContext context) {return new JsonPrimitive (src); }}Entonces el uso es así:
return new Retrofit.Builder () .Client (OKHTTPClient) // Establecer Network Access Framework.AddConverterFactory (gsonConverFactory.Create (buildGson ()) // Agregar JSON Conversion Framework.addCalladapTorory (RxJavacallApterFactory.Create.Create ()) // LetRofit Support RAXJAVA.BeRLAVA.BASE.BASE.BASE.BASE.BASE.BASE.BASERLAVA.BASERLAVA.BASEAT .Build ();/** * Agregue el procesamiento de "" y "nulo" en el fondo * 1.int => 0 * 2.Double => 0.00 * 3.long => 0l * * @return */public static gson buildgson () {if (gson == null) {gson = new GsonBuilder () .RegheryPeadPeadapter (Integer.class, New Intepter) .RegisterTypeAdapter (int.class, new IntegerDefault0Adapter ()) .RegisterTypeAdapter (Double.Class, New Doubledefault0Adapter ()) .RegisteryPeadapter (Long.Class, New Longdefault0Adapter ()) .RegisteryPeApter (Long.class, New LongDefault0Adapter ().).).).).).).). } return gson;}Nunca se bloqueará porque el campo JSON de fondo está vacío nuevamente
Resumir
Lo anterior es todo el contenido de este artículo. Espero que el contenido de este artículo sea útil para el estudio o el trabajo de todos. Si tiene alguna pregunta, puede dejar un mensaje para comunicarse.