【问题标题】:parsing JSON array of objects with gson使用 gson 解析 JSON 对象数组
【发布时间】:2015-09-17 12:59:27
【问题描述】:

我正在尝试使用 gson 解析包含对象数组的 JSON 文件。我在这行代码中收到“线程“主”com.google.gson.JsonSyntaxException:java.io.EOFException:第 1 行第 2 列输入结束”错误:

  RecipeList[] myRecipe = gson.fromJson(theLine, RecipeList[].class);

我对使用 gson 有点困惑,所以我认为我没有正确设置。数据格式如下:

[  {
"id": 10259,
"cuisine": "greek",
"ingredients": [
  "romaine lettuce",
  "black olives"
]  }, {
"id": 25693,
"cuisine": "southern_us",
"ingredients": [
  "plain flour",
  "ground pepper",
  "salt",
  "tomatoes",
  "ground black pepper",
  "thyme"
]  }]

试图读取的代码是:

inputStream = new FileReader("filepath\\file.json");
BufferedReader myReader = new BufferedReader(inputStream);
theLine = myReader.readLine();

Gson gson = new Gson();
RecipeList[] myRecipe = gson.fromJson(theLine, RecipeList[].class);

我的RecipeList类,本来打算把recipe对象数组存储在json文件中(不过我觉得这肯定是错的)

ArrayList<Recipe> recipeArray;

public RecipeList (Recipe recipObj){
    recipeArray.add(recipObj);
}

还有我的Recipe类,用于在json数组中创建每个recipe对象:

String recipeID;
String cuisine;
ArrayList<String> ingredients;


public Recipe (String id, String cuisine, ArrayList<String> ingredients){
    this.recipeID = id;
    this.cuisine = cuisine;
    for (int k = 0; k < ingredients.size(); k++){
        this.ingredients.add(ingredients.get(k));
    }
}  

感谢您的帮助。我对使用 gson 读取 json 文本以及如何从该数组创建单个对象感到有些困惑。

谢谢 丽贝卡

【问题讨论】:

    标签: java arrays json gson


    【解决方案1】:

    theLine = myReader.readLine();

    您需要从文件中读取所有行,直到 eof。

    例如:

        br = new BufferedReader(new FileReader("C:\\testing.txt"));
    
    String line="";
                    while ((line = br.readLine()) != null) {
                        theLine+=line;
                    }
    

    【讨论】:

    • 这似乎有助于清除错误消息。我不知道其余的是否正在工作,因为它仍在读取该文件(它非常大)。鉴于它是一个大文件,有没有办法在不让它变成 1 个长字符串的情况下处理它? json文件中的行分隔符是什么?是在数组中的每个对象之后,还是任意的?
    • 实际上你必须阅读完整的文件。文件的格式不会改变它的 JSON 或其他文件。在将其解析为 GSON 之前,您需要一个完整的 JSON。我找不到任何帮助。但是如果你认为 StringBuilder 占用 java heap 很多,你可以使用 StringBuilder 来代替。
    • 我认为您可以从 InputStream 解析 GSON 而不是使用 String 也可以提供帮助。 Gson gson = 新 Gson();阅读器 reader = new InputStreamReader(source); SearchResponse 响应 = gson.fromJson(reader,SearchResponse.class);这里的源将是您的文件。
    • 谢谢。我确实尝试过使用“}”作为分隔符,因为当我输出几行时,它似乎在自己的一行上:while ((line = myReader.readLine()) != null) { while ((line .compareTo("},") != 0)) { theLine += line; } - 但它只是连接了“{”并且不匹配任何其他内容
    • 刚刚尝试编辑我上面的评论,说 compareTo 不起作用,因为字符串包含一些额外的字符,可能是空格。匹配作为子字符串有效。我可能会尝试查看是否可以一次提取一个 JSON 对象 1 个对象,然后将其传递给 gson 以反序列化
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    相关资源
    最近更新 更多