[英]Parse array of objects as array of String using Gson
I have a big JSON file (> 1Gb) which includes an array of objects: 我有一个大的JSON文件(> 1Gb),其中包含一个对象数组:
[
{
"Property1":"value",
"Property2":{
"subProperty1":"value",
"subProperty2":[
"value",
"value"
]
},
"Property3":"value"
},
{
"Property1":"value",
"Property2":{
"subProperty1":"value",
"subProperty2":[
"value",
"value"
]
},
"Property3":"value"
}
]
Currently, I parse this JSON using Gson but it doesn't work, I have following error: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
目前,我使用Gson解析此JSON但它不起作用,我有以下错误:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
In order to parse this JSON, I did following: 为了解析这个JSON,我做了以下事情:
reader = new BufferedReader(new FileReader(jsonFile));
Gson gson = new GsonBuilder().create();
Type typeArray = new TypeToken<List<String>>(){}.getType();
List<String> topics = gson.fromJson(reader, typeArray);
I want to parse this JSON array as String Array. 我想将这个JSON数组解析为String Array。 In other words, I want a Java list of string instead of a Java list of objects.
换句话说,我想要一个字符串的Java列表而不是Java的对象列表。 Like that :
像那样 :
topics[0] = "{\"Property1\":\"value\",\"Property2\":{\"subProperty1\":\"value\",\"subProperty2\":[\"value\",\"value\"]},\"Property3\":\"value\"}";
topics[1] = "{\"Property1\":\"value\",\"Property2\":{\"subProperty1\":\"value\",\"subProperty2\":[\"value\",\"value\"]},\"Property3\":\"value\"}";
Thank you :) 谢谢 :)
Something like this should work: 这样的事情应该有效:
public List<String> convertToStringArray(File file) throws IOException {
List<String> result = new ArrayList<>();
String data = FileUtils.readFileToString(file, "UTF-8");
JsonArray entries = (new JsonParser()).parse(data).getAsJsonArray();
for (JsonElement obj : entries)
result.add(obj.toString());
return result;
}
I used file reader from apache.commons.io
, but you could replace that with native Java reader... Also, if you need that topics[0] =
in each string you could add that with: 我使用了
apache.commons.io
文件阅读器,但你可以用本机Java阅读器替换它...而且,如果你需要在每个字符串中使用topics[0] =
你可以添加以下内容:
result.add(String.format("topics[%s] = %s", result.size(), obj.toString()));
These are used imports from gson: 这些是从gson使用的导入:
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.