![](/img/trans.png)
[英]Using GSON to parse an array of objects that contains an object that contains a needed String
[英]Parse array of objects as array of String using Gson
我有一个大的JSON文件(> 1Gb),其中包含一个对象数组:
[
{
"Property1":"value",
"Property2":{
"subProperty1":"value",
"subProperty2":[
"value",
"value"
]
},
"Property3":"value"
},
{
"Property1":"value",
"Property2":{
"subProperty1":"value",
"subProperty2":[
"value",
"value"
]
},
"Property3":"value"
}
]
目前,我使用Gson解析此JSON但它不起作用,我有以下错误: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
为了解析这个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);
我想将这个JSON数组解析为String Array。 换句话说,我想要一个字符串的Java列表而不是Java的对象列表。 像那样 :
topics[0] = "{\"Property1\":\"value\",\"Property2\":{\"subProperty1\":\"value\",\"subProperty2\":[\"value\",\"value\"]},\"Property3\":\"value\"}";
topics[1] = "{\"Property1\":\"value\",\"Property2\":{\"subProperty1\":\"value\",\"subProperty2\":[\"value\",\"value\"]},\"Property3\":\"value\"}";
谢谢 :)
这样的事情应该有效:
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;
}
我使用了apache.commons.io
文件阅读器,但你可以用本机Java阅读器替换它...而且,如果你需要在每个字符串中使用topics[0] =
你可以添加以下内容:
result.add(String.format("topics[%s] = %s", result.size(), obj.toString()));
这些是从gson使用的导入:
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.