Handling method of exception when gson parses empty string

preface

In actual development projects, the server often uses the empty string "" as the return result to represent the null value, but this will encounter problems in gson. If the data type is not a string, gson will report an error

Jason anomaly

Let's first look at a JSON returned in the background

Normally, JSON:

Entity class corresponding to data part:

Exception JSON (the corresponding data is not found in the newsId field of the background database):

In this way, gson will throw an exception of parsing error during parsing, and the app crashes because it cannot convert '' to int

JSON exception handling

We expect that the JSON exception returned in the background can also be parsed successfully, and the corresponding null value is converted to the default value, such as newsId = 0;

It excludes the background developers from correcting you when outputting. You still have to rely on yourself---

To write a type converter for int values, we need to implement gson's jsonserializer < T > interface and jsondeserializer < T >, that is, serialization and deserialization interfaces

Similarly, long and double types

double=>

long=>

So the usage is as follows:

It will never crash because the background JSON field is empty

summary

The above is the whole content of this article. I hope the content of this article can be helpful to your study or work. If you have any questions, you can leave a message.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>