سؤال

Json String

{"userName":null," msgArr":[null],"numrow":0} //String result

Gson

new Gson().fromJson(result, MyClass.class);

MyClass

public String userName;
public int[] msgArr;
...

Error Stack

at java.lang.IllegalArgumentException: Primitive array can't take null values.
at java.lang.reflect.Array.set(Array.java:406)
at com.google.gson.internal.bind.ArrayTypeAdapter.read(ArrayTypeAdapter.java:78)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
at com.google.gson.Gson.fromJson(Gson.java:803)
at com.google.gson.Gson.fromJson(Gson.java:768)
at com.google.gson.Gson.fromJson(Gson.java:717)
at com.google.gson.Gson.fromJson(Gson.java:689)
at com.test.dao.RequestBase.onPostExecute(RequestBase.java:79)

How can avoid this exception if I can not change json string "msgArr=[null]"?

هل كانت مفيدة؟

المحلول

user2507946 has the right answer in your comments.

int is not nullable in Java but you can substitute the wrapper class Integer to handle null values.

Example

public String userName;
public Integer[] msgArr;
...

نصائح أخرى

Gson gson = new GsonBuilder
     .serializeNulls()
     .create();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top