java无法使用GSON解析JSON文件
我有一个非常简单的JSON文件,需要从中获取字段名和值。我在eclipse中使用Java1.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文档,非常糟糕。在不知道字段名的情况下,我找不到任何用于提取值的方法。谢谢
# 1 楼答案
这是我的现成解决方案
你写的一些笔记
header
是一个只包含一个JSON对象的数组,对于JSON的其余部分也是如此。如果你控制着JSON,你可以简化它header
下的字段,但它是一个数组,所以你必须先把它解包并得到第一个位置我没有使用
Gson
类,因为它通常与Braj提供的类层次结构一起工作得更好。有了JsonParser,假设“结构”没有太大变化,您就更灵活了。也就是说,您有一个包含数组的对象,其中只有一个元素是映射所以这条线
基本上遍历JSON以获得正确的信息。我忘记了:这是我代码的结果: