简体   繁体   English

使用gson库读取json文件

[英]Read a json file with gson library

I have a json file formatted as the following: 我有一个json文件格式如下:

[{
  'title':    'Java',
  'authors':  ['Auth', 'Name']
},
{
  'title':    'Java2',
  'authors':  ['Auth2', 'Name2']
},
{
  'title':    'Java3',
  'authors':  ['Auth3', 'Name3']
}]

So i've tried using gson library to parse the file, with the following code: 所以我尝试使用gson库来解析文件,使用以下代码:

JsonElement jelement = new JsonParser().parse(pathFile);
        JsonObject jObject = jelement.getAsJsonObject();
        JsonArray jOb = jObject.getAsJsonArray("");
        final String[] jObTE = new String[jOb.size()];
        for (int k=0; k<jObTE.length; k++) {
            final JsonElement jCT = jOb.get(k);
            JsonObject jOTE = jCT.getAsJsonObject();
            JsonArray jContentTime = jOTE.getAsJsonArray("content_time");
            final String[] contentTime = new String[jContentTime.size()];
            for (int i=0; i<contentTime.length; i++) {
                final JsonElement jsonCT = jContentTime.get(i);
                JsonObject jObjectTE = jsonCT.getAsJsonObject();
                JsonArray jTE = jObjectTE.getAsJsonArray("");
                final String[] contentTimeTE = new String[jTE.size()];
                for (int j=0; j<contentTimeTE.length; j++) {
                    final JsonElement jsonCTTE = jTE.get(j);
                    contentTime[j] = jsonCTTE.getAsString();
                }
            }
        }

But, in doing so, i found this error: java.lang.IllegalStateException: Not a JSON Object at the second line. 但是,在这样做时,我发现了这个错误: java.lang.IllegalStateException: Not a JSON Object第二行java.lang.IllegalStateException: Not a JSON Object

You're trying to parse array to object, in which case you'll fail, because top level structure in your json is array. 您正在尝试将数组解析为对象,在这种情况下您将失败,因为您的json中的顶级结构是数组。

I would parse this JSON in slightly different way 我会以稍微不同的方式解析这个JSON

1) Create some Model class 1)创建一些Model

public class Model {
    private String title;
    private List<String> authors;
//getters ...
}

2) Parse your JSON ( 2)解析你的JSON(

public static final String JSON_PATH = "/Users/dawid/Workspace/Test/test.json";

Gson gson = new Gson();
BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
Type type = new TypeToken<List<Model>>(){}.getType();
List<Model> models = gson.fromJson(br, type);

Your code is barely readable, so i guess that solved your problem 你的代码几乎无法读取,所以我想这解决了你的问题

Second way: 第二种方式:

BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(br).getAsJsonArray();

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

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