Gson parsing an exception to an empty string _java

Source: Internet
Author: User
Tags parse error

Objective

In the actual development project, the server often uses the empty string "" as the return result indicates the null value, but this will encounter the problem in the Gson, if this data type is not the string, Gson parsing will be the error

JSON exception condition

Let's look at a background-returned JSON

Under normal conditions JSON:

{"
 code": 0,
 "msg": "OK",
 "data": {
  "id": 5638,
  "newsId": 5638
 }
}

The entity class corresponding to the data section:

public class 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;
 }
}

exception Condition JSON (The Background Database NewSID field is not queried for the corresponding data):

{"
 code": 0,
 "msg": "OK",
 "data": {
  "id": 5638,
  "newsId": ""
 }
}

So Gson throws a parse error exception when parsing, and the app crashes because it can't convert "" to int

Processing of JSON exceptions

We expect the JSON exception returned in the background to parse successfully, and the null value will be converted to the default value, such as:newsId=0;

This eliminates the background developer output when you do corrective, or to rely on their own ah---

We write a type converter for int value, we need to implement Gson JsonSerializer<T> interface and JsonDeserializer<T> , that is, serialization and deserialization interface

public class Integerdefault0adapter implements Jsonserializer<integer>, jsondeserializer<integer> {
 @Override Public
 Integer Deserialize (jsonelement json, Type Typeoft, Jsondeserializationcontext context)
   Throws Jsonparseexception {
  try {
   if (json.getasstring). Equals ("") | | Json.getasstring (). Equals ("null")) {//defined as int type, if background returns "" or null, returns 0 return
    0;
   }
  catch (Exception Ignore) {
  }
  try {return
   json.getasint ();
  } catch (NumberFormatException e) {
   throw new Jsonsyntaxexception (e);
  }

 @Override public
 jsonelement Serialize (Integer src, Type typeofsrc, Jsonserializationcontext context) {
  return new jsonprimitive (SRC);
 }

Same long and double type

Double=>

public class Doubledefault0adapter implements Jsonserializer<double>, jsondeserializer<double> {
 @ Override Public
 Double Deserialize (jsonelement json, Type Typeoft, Jsondeserializationcontext context) throws jsonparseexception {
  try {
   if (json.getasstring). Equals ("") | | Json.getasstring (). Equals ("null")) {//defined as the double type, if the background returns "" or NULL, returns 0.00 return
    0.00;
  }
   catch ( Exception ignore) {
  }
  try {return
   json.getasdouble ();
  } catch (NumberFormatException e) {
   throw new Jsonsyntaxexception (e);
  }
 }

 @Override public
 jsonelement Serialize (Double src, Type typeofsrc, Jsonserializationcontext context) {
  return new jsonprimitive (SRC);
 }

Long=>

public class Longdefault0adapter implements Jsonserializer<long>, jsondeserializer<long> {
 @Override Public
 Long Deserialize (jsonelement json, Type Typeoft, Jsondeserializationcontext context)
  throws jsonparseexception {
  try {
   if (json.getasstring). Equals ("") | | Json.getasstring (). Equals ("null")) {//defined as a long and if the background returns "" or null, returns 0 return
     0l;
    }
   catch (Exception Ignore) {
  }
  try {return
   json.getaslong ();
  } catch (NumberFormatException e) {
   throw new Jsonsyntaxexception (e);
  }

 @Override public
 jsonelement Serialize (Long src, Type typeofsrc, Jsonserializationcontext context) {
  return New Jsonprimitive (SRC);
 }
}

So the use is this:

return new Retrofit.builder ()
  . Client (okhttpclient)/Set the network Access Framework
  . Addconverterfactory ( Gsonconverterfactory.create (Buildgson ())//Add JSON Transformation Framework
  . Addcalladapterfactory ( Rxjavacalladapterfactory.create ())//Let retrofit support Rxjava
  . BaseURL (BaseURL)
  . Build ();

/**
 * Increase background return "" and "null" processing
 * 1.int=>0 *
 2.double=>0.00
 * 3.long=>0l
 * * @return
 */Public
static Gson Buildgson () {
 if (Gson = null) {
  Gson = new Gsonbuilder ()
    . Registertypea Dapter (Integer.class, New Integerdefault0adapter ())
    . Registertypeadapter (Int.class, new Integerdefault0adapter ())
    . Registertypeadapter (Double.class, New Doubledefault0adapter ())
    . Registertypeadapter (Double.class, New Doubledefault0adapter ())
    . Registertypeadapter (Long.class, new Longdefault0adapter ())
    . Registertypeadapter (Long.class, New Longdefault0adapter ())
    . Create ();
 return Gson;
}

It's never going to crash because the background JSON field is empty.

Summarize

The above is the entire content of this article, I hope the content of this article for everyone's study or work can help, if there is doubt you can message exchange.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.