3

json字符串

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

格森

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

我的课

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

错误堆栈

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)

如果我无法更改 json 字符串“msgArr=[null]”,如何避免此异常?

4

2 回答 2

0

user2507946 在您的评论中有正确的答案。

int在 Java 中不可为空,但您可以替换包装类Integer来处理空值。

例子

public String userName;
public Integer[] msgArr;
...
于 2013-08-02T02:28:55.183 回答
0
Gson gson = new GsonBuilder
     .serializeNulls()
     .create();
于 2013-08-02T02:29:19.633 回答