java - 无法使用 GSON 解析 JSON 文件

标签 java json gson

我有一个非常简单的 JSON 文件,我需要从中获取字段名称和值。我在 Eclipse 中使用 Java 1.7 和 gson。这是我的 JSON 文件:

{
   "header": [
      {
         "document_number": "document_number",     
         "report": "report",
         "version": "version"
      }
   ],

   "summary": [
      {
         "row_type": "row_type",
         "crs_id": "crs_id",
         "report_begin": "report_begin",
         "report_end": "report_end",
         "gross_tax": "gross_tax",
         "compensating_tax": "compensating_tax",
         "withholding_tax": "withholding_tax",
         "total_due_tax": "total_due_tax",
         "penalty": "penalty",
         "interest": "interest",
         "total_due_due": "total_due_due"
      }
   ],

   "detail": [

      {

         "row_type": "row_type",
         "county_name": "county_name",
         "rate_type": "rate_type",
         "location_code": "location_code",
         "gross_receipts": "gross_receipts",
         "deductions": "deductions",
         "taxable_gross_receipts": "taxable_gross_receipts",
         "tax_rate": "tax_rate","gross_tax": "gross_tax"

      }

   ]

}

我需要在不知道不同字段名称的情况下导航文件。在我看来,我想加载 JSON 文件,然后返回第一个字段值(在本例中为 header )。然后返回该根下的字段名称和值。抱歉,如果我的术语不准确,我是 JSON 新手。我在网上找到了不同的 gson 文档,它们都很糟糕。如果不知道字段名称,我找不到任何用于提取值的内容。谢谢

最佳答案

这是代码。欲了解更多信息,请阅读内联评论或询问我。

创建一些 POJO 类作为 JSON 字符串的副本。

class MyJSON {
    ArrayList<Header> header;
    ArrayList<Summary> summary;
    ArrayList<Detail> detail;
}

class Header {
    String document_number;
    String report;
    String version;
}
// create classes for Summary and Detail as well in the similar way of Header
// the variable name must be same as it is in JSON string along with case.

...

// read JSON from the file
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(new File("resources/json1.txt")));
String line = null;
while ((line = reader.readLine()) != null) {
    builder.append(line);
}
reader.close();

// create a new Gson object
Gson gson = new Gson();
// convert JSON string to POJO object
MyJSON object = gson.fromJson(builder.toString(), MyJSON.class);

// printing only header
for (Header header : object.header) {
    System.out.println(header.document_number + ", " + header.report + ", "
            + header.version);
}

输出(仅打印标题)

document_number, report, version

关于java - 无法使用 GSON 解析 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23704415/

相关文章:

java - 通过java运行linux命令。

android - 仅显示来自 json 调用的某些数据

java - Gson fromJson 和 toJson 用于 Java 中返回 null 的简单对象

java - GSON:对对象映射进行编码并在解码时保留类型

java - 使用构造函数初始化数组中的值的最佳方法是什么?

java - SWT 文本焦点和默认选择(返回键)事件

java - Android 将按钮或 View 保留在应用程序内所有 Activity 的前面,而不使用 baseActivity

java - 解决 JSONException 重复键

json - 在 scrapy 中将 json 参数传递给蜘蛛

java - GSON可以是字符串数组或对象数组