Parsing an array of objects as a String array using Gson

I have a large JSON file (> 1Gb) that 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"
   }
]

      

I am currently parsing this JSON using Gson, but it doesn't work, I have the following error: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

To parse this JSON, I did the 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 list of Java strings instead of a list of Java objects. For example:

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:)

+3


source to share


1 answer


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 have used a file reader since apache.commons.io

, but you can replace it with the built-in Java reader ... Also, if you need this topics[0] =

on every line, you can add this with



result.add(String.format("topics[%s] = %s", result.size(), obj.toString()));

      

Import from gson is used:

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

      

+2


source







All Articles