gpt4 book ai didi

android - 使用 JsonReader 解析时 JsonArray 或 JsonObject 为 null

转载 作者:行者123 更新时间:2023-11-29 18:03:17 24 4
gpt4 key购买 nike

我正在尝试使用 JsonReader 解析 json。在解析时,我遇到了 2 个应用程序崩溃的场景。1).当 JsonArray 包含另一个 JsonArrays 的集合并且其中一个为空时。我给出的场景是结果是一个数组,其中还有 21 个数组,最后一个数组为空。

"results": [(21)
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[...(5)],-
[(0)]
],

2).当 JsonArray 中有一组对象并且其中一个对象为空时。我附上了同样的例子。在这里,我的源作为我的 JsonArray,它包含 21 个对象,其中 1 个为空。

"source": [(21)
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
{...},-
null
]

我可以通过

检查 a 中的某个单独元素何时为 null
reader.peek()== JsonToken.NULL

Logcat 中的错误输出:

02-04 16:10:02.425: E/AndroidRuntime(1203): FATAL EXCEPTION: pool-1-thread-2
02-04 16:10:02.425: E/AndroidRuntime(1203): java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NULL at line 1 column 327992
02-04 16:10:02.425: E/AndroidRuntime(1203): at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
02-04 16:10:02.425: E/AndroidRuntime(1203): at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)

我不知道如何检查我要解析的没有名称的数组或对象是否为 Null。

编辑:

代码:

public ResultObject parse(){
try{
if(reader != null ){
resultObject = new ResultObject();
reader.beginObject();
Log.e("123", "inside try ");
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equalsIgnoreCase("id")) {
if(reader.peek()== JsonToken.NULL){
reader.skipValue();
id= 0;
Log.e("123", "parse result --------id----------" + id);
resultObject.setId(id);
}else{
id= reader.nextDouble();
Log.e("123", "parse result -------id----------" + id);
resultObject.setId(id);
}
} else {
Log.e("123", "skip value");
reader.skipValue();
}
}

reader.endObject();
}
}catch(IOException e){
e.printStackTrace();
}

return resultObject;
}

调用函数:

if (name.equalsIgnoreCase(SOURCE)) {
if(reader.peek()== JsonToken.NULL){
reader.skipValue();
} else {
resultObjectList = new ArrayList();
resultObject = new ResultObject();
reader.beginArray();
while(reader.hasNext()){
resultObject =new ResultJsonUtil(reader).parse();
if(resultObject!=null){
resultObjectList.add(resultObject);
}
}

reader.endArray();
}
}

最佳答案

您的代码似乎在 reader.beginObject(); 处崩溃。由于没有对象,Gson 抛出异常。

如果您不确定接下来会发生什么,您可以使用 peek 进行测试

Returns the type of the next token without consuming it.

然后您可以根据检索到的 JsonToken 调用适当的阅读器方法

if (reader.peek() != JsonToken.BEGIN_OBJECT) {
// do something
} else {
// parse object
resultObject = new ResultObject();
reader.beginObject();
...
}

关于android - 使用 JsonReader 解析时 JsonArray 或 JsonObject 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14685015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com