list of strings can not be converted to gson.JsonElement

501 views Asked by At

I have want to create a jsonObject in java of this type:

"a": "b",
"c": {
  "d": {
    "e": [
      "f",
      "g",
      "h"
    ]
  }
}

Following is a snippet of the code where I try to add the value of "e" given in the form of the list:

import com.google.gson.JsonObject;
import java.util.ArrayList;
List<String> arr = new ArrayList<String>();
arr.add("f");
arr.add("g");
arr.add("h");
JsonObject arrayList = new JsonObject();
arrayList.add("e", arr);

In this portion I am getting an error:

java.util.List<java.lang.String> cannot be converted to com.google.gson.JsonElement

Any suggestion to resolve this issue will be appreciated. Thanks!

2

There are 2 answers

6
Saad Sahibjan On BEST ANSWER

Try the following

arrayList.add("e", gson.toJsonTree(arr));
2
Michael Sims On

This compiled and ran without error for me:

List<String> arr = new ArrayList<String>();
arr.add("f");
arr.add("g");
arr.add("h");
JsonObject arrayList = new JsonObject();
Gson gson = new Gson();
arrayList.add("e", gson.toJsonTree(arr));