提问人:Tiana 提问时间:6/16/2023 最后编辑:Tiana 更新时间:6/17/2023 访问量:41
如何在android中解析JSON文件,同时跳过具有null值的项目
How to parse a JSON file in android while skipping items with null values
问:
我的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;
注释掉的部分是我让它工作的各种尝试。它现在读取文件而不会崩溃,但不会解析为对象。
答:
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 和空值。
评论