我有一个非常简单的 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/