如何在android中解析JSON文件,同时跳过具有null值的项目

How to parse a JSON file in android while skipping items with null values

提问人:Tiana 提问时间:6/16/2023 最后编辑:Tiana 更新时间:6/17/2023 访问量:41

问:

我的JSON文件的一部分:

[
{"id": 755, "listId": 2, "name": ""},
{"id": 203, "listId": 2, "name": ""},
{"id": 684, "listId": 1, "name": "Item 684"},
{"id": 276, "listId": 1, "name": "Item 276"},
{"id": 736, "listId": 3, "name": null},
{"id": 926, "listId": 4, "name": null},
{"id": 808, "listId": 4, "name": "Item 808"}]

我想将 JSON 文件解析为 Item 对象,同时跳过 null 值。但是我现在从 gson 收到错误

com.google.gson.JsonSyntaxException:java.lang.IllegalStateException: 预期BEGIN_ARRAY,但在第 2 行第 2 列路径 $[0] 处BEGIN_OBJECT

private String deserializeItem() throws IOException, JSONException {
        String itemText = "";
        //Item item = new Item();
        Gson gson = new Gson();

        InputStream is = getAssets().open("JSONFile.json");
        String jsonTxt = IOUtils.toString(is, "UTF-8");
        //Map map = gson.fromJson(jsonTxt, Map.class);
        //Map<String,Item> map = new HashMap<String, Item>();
        //map = (Map<String,Item>) gson.fromJson(jsonTxt, map.getClass());
        //List<Item> itemList = Arrays.asList(gson.fromJson(jsonTxt, Item[].class));
        //Item item = gson.fromJson(jsonTxt, Item.class);
        JsonElement json = gson.fromJson(new FileReader("fetchJSONFile.json"), JsonElement.class);
        String result = gson.toJson(json);

        System.out.println(jsonTxt);
        //JSONObject json = new JSONObject(jsonTxt);
        //String a = json.getString("1000");
        //System.out.println(a);

        return itemText;

注释掉的部分是我让它工作的各种尝试。它现在读取文件而不会崩溃,但不会解析为对象。

java android json

评论

0赞 shmosel 6/16/2023
请更具体地说明哪些不起作用。
1赞 Jhilton 6/16/2023
JSONObject 期望字符串是 JSON 字符串,而不是文件的路径。也许这个链接可能会有所帮助 stackoverflow.com/a/20090084/9520479
0赞 Tiana 6/16/2023
尝试了链接中的内容,但是当它尝试运行 inputStream 时,它会因 IOException 而崩溃
0赞 Tiana 6/16/2023
好的,发现我的方法是静态的,在解析时搞砸了。这是固定的,但它仍然不会映射到一个对象上,给我一个com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY,但在第 2 行第 2 列路径 $[0] 错误处BEGIN_OBJECT

答:

0赞 Tiana 6/17/2023 #1

好吧,我想通了我的问题。首先,我需要使我的方法非静态,这允许我通过 InputStream 读取 JSON 文件。然后我需要使用数组(但不是列表......出于某种原因?将所有 JSON 数据映射到对象。最后,我的代码如下所示:

 private String deserializeItem() throws IOException, JSONException {
    String itemText = "";
    Gson gson = new Gson();
    InputStream is = getAssets().open("JSONFile.json");
    String jsonTxt = IOUtils.toString(is, "UTF-8");
    Item[] items = gson.fromJson(jsonTxt, Item[].class);
    List<Item> itemList = new ArrayList<Item>();

    //Eliminates objects with null and empty item names
    for (int i=0; i<items.length; i++)
    {
        if (items[i].getItemName() == null) {continue;}
        else if (items[i].getItemName().equals("")) {continue;}
        else {itemList.add(items[i]);}
    }

这让我可以将 JSON 文件解析为对象并删除其中的所有 null 和空值。