I have a big JSON file (> 1Gb) which includes an array of objects:
[
{
"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 $
In order to parse this JSON, I did following:
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. In other words, I want a Java list of string instead of a Java list of objects. 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:
result.add(String.format("topics[%s] = %s", result.size(), obj.toString()));
These are used imports from gson:
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.