[英]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.