Search code examples
javajsongsonproperties-file

Parse Json from Java properties file using gson library


I need to read and parse a json array from java properties file. I'm able to read the properties file and get the json array String. But I'm unable to parse the json array and get the values. I'm using gson library. Here is the data from properties file

jsonarray = [ { key1 : value1, key2 : value2 } ]

Code:

Properties properties = new Properties();
properties.load(new FileInputStream(filePath));
String jsonArray = properties.getProperty("jsonarray")
JsonElement element = new JsonPrimitive(jsonArray);
JsonArray array = element.getAsJsonArray();

I'm getting IllegalStateException

java.lang.IllegalStateException: Not a JSON Array: "[ { key1 : value1, key2 : value2 } ]"

The problem is it is taking extra double quotes at the beginning and at the end.

I have tried adding quotes to keys and values, but with no success. I need to use gson library itself, so please don't suggest other libraries. I cannot create a POJO class for it and use new Gson().fromJson(jsonArray), so kindly please don't suggest that also.

I've searched and tried a lot without success. The method I referred is given here

Thanks in advance

Edit 1: I've tried the following in properties file

jsonarray = [ { "key1" : "value1", "key2" : "value2" } ]

and I got same exception like

java.lang.IllegalStateException: Not a JSON Array: "[ { \"key1\" : \"value1\", \"key2\" : \"value2\" } ]"

I tried to create a JsonArray object in code and print it

JsonArray array = new JsonArray();
JsonObject object = new JsonObject();
object.addProperty("key1", "value1");
object.addProperty("key2", "value2");
array.add(object);
System.out.println(array.toString());

The output was as below

[{"key1":"value1","key2":"value2"}]

Solution

  • The Javadoc of JsonPrimitive you've used here

    JsonElement element = new JsonPrimitive(jsonArray);
    

    states

    Create a primitive containing a String value.

    When you then do

    JsonArray array = element.getAsJsonArray();
    

    it'll obviously fail because element is a JSON String, not a JSON array. Just parse the JSON directly

    JsonArray array = new Gson().fromJson(jsonArray, JsonArray.class)
    

    This is all after you've changed your properties file content to be actual JSON

    jsonarray = [ { "key1" : "value1", "key2" : "value2" } ]