java 使用 gson 库读取 json 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34486503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read a json file with gson library
提问by user2520969
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
在第二行。
回答by dawidklos
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();