简体   繁体   English

无法使用GSON解析JSON文件

[英]Cannot parse JSON file with GSON

I have a pretty simple JSON file that I need to get the field names and values out of. 我有一个非常简单的JSON文件,我需要从中获取字段名称和值。 I'm using Java 1.7 with gson in eclipse. 我在eclipse中使用Java 1.7和gson。 Here is my JSON file: 这是我的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"

      }

   ]

}

I need to navigate the file withour knowing the different field names. 我需要在知道不同字段名称的情况下浏览文件。 In my mind I want to load the JSON file, then return the first field value (in this case header). 我想加载JSON文件,然后返回第一个字段值(在本例中为header)。 And then return the field names and values under that root. 然后返回该根目录下的字段名称和值。 Sorry if my terminology is off, I'm new to JSON. 抱歉,如果我的术语不对,我是JSON新手。 I've found different gson documentation online and its all horrible. 我在网上找到了不同的gson文档,这些文档都很糟糕。 I couldn't find anything for pulling values without knowing the field names. 在不知道字段名称的情况下,我找不到任何用于提取值的东西。 Thanks 谢谢

Here is the code. 这是代码。 For more info read inline comments or ask me. 有关更多信息,请阅读嵌入式注释或询问我。

Create some POJO classes that is replica of your JSON string. 创建一些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);
}

output (printing only header) 输出(仅打印标题)

document_number, report, version

This is my ready to run solution. 这是我准备运行的解决方案。

package stackoverflow.questions;

import java.util.*;

import com.google.gson.*;

public class Q23704415 {

    public static void main(String[] args) {
       String 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\"       "+
               "                                                                       "+
               "      }                                                                "+
               "                                                                       "+
               "   ]                                                                   "+
               "                                                                       "+
               "}                                                                      ";


         JsonElement root = new JsonParser().parse(json);
         JsonObject jo = root.getAsJsonObject();

         JsonObject header = jo.get("header").getAsJsonArray().get(0).getAsJsonObject();

         Set<Map.Entry<String, JsonElement>> set = header.entrySet();
         for(Map.Entry<String, JsonElement> e : set){
             System.out.println(e.getKey() + "->" + e.getValue());
         }



    }

}

Some notes on what you wrote. 关于您所写内容的一些注释。

  1. Your JSON is a bit weird, header for example, is an array that contains one JSON object only and the same is for the rest of the JSON. 您的JSON有点奇怪,例如header ,它是一个仅包含一个JSON对象的数组,其余的JSON也是如此。 If you are in control of JSON you can simplify it 如果您控制JSON,则可以简化它
  2. You said that you want the "first" field, but root element of you JSON is an object ie a map ie an associative array, so "first" makes no sense here so you can access by name and not by position 您说过要“第一个”字段,但是JSON的根元素是一个对象,即一个地图,即一个关联数组,因此“第一个”在这里没有意义,因此您可以按名称而不按位置进行访问
  3. You said that you want field under header but it's an array so you have to unpack it first and get first position 您说过要在headerheader字段,但它是一个数组,因此必须先将其拆包并获得第一个位置

I did not use Gson class since it usually works better with a class hierarchy as the one Braj provided you with. 我没有使用Gson类,因为它通常与Braj为您提供的类层次结构一起更好地工作。 With JsonParser you are more flexible assuming that the "structure" does not change too much. 使用JsonParser,您可以更灵活地假设“结构”的变化不大。 That is, you have an object that contains arrays with only one element that is a map. 也就是说,您有一个对象,其中包含的数组仅包含一个作为映射的元素。

So this line 所以这条线

JsonObject header = jo.get("header").getAsJsonArray().get(0).getAsJsonObject();

essentially traverse your JSON to get to the right info. 本质上遍历您的JSON以获得正确的信息。 I was forgetting: this is the result of my code: 我忘记了:这是我的代码的结果:

document_number->"document_number"
report->"report"
version->"version"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM