0

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 Answers2

0

Try the following

arrayList.add("e", gson.toJsonTree(arr));
Saad Sahibjan
  • 300
  • 1
  • 6
  • Thanks Saad. Now that line compiles. However, in the next line I am getting the error: actual and formal argument lists differ in length – Coding Practice Feb 06 '21 at 14:41
  • Thanks Saad. Now that line compiles. However, I have the following as well: JsonArray arrayJson Json = new JsonArray(); arrayJson.add("d", arrayList). Here I am getting the error reason: actual and formal argument lists differ in length. Don't know why ? – Coding Practice Feb 06 '21 at 14:48
  • JsonObject dObj = new JsonObject(); dObj.add("d", arrayList); System.out.println(dObj); – Saad Sahibjan Feb 06 '21 at 14:55
  • Thanks Saad. That works. But let's say if I have like "a": "b", "c": { "d": { "e": [ "f", "g", "h" ] "i" : [ "j", "k", "l", ] } } then should I use an JsonArray and how ? – Coding Practice Feb 06 '21 at 15:01
  • You can create and put the "e" and "i" object into a list and add that list to "d" – Saad Sahibjan Feb 06 '21 at 15:18
  • Thanks Saad. My bad. Wanted to ask about a slighlty different structure. Cen you help me with the following structure. "a": "b", "c": { "d": { "e": [ "f", "g", "h" ] }, { "i" : [ "j", "k", "l" ] } } } Should I still use a list or an array ? – Coding Practice Feb 06 '21 at 15:34
0

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));
Michael Sims
  • 2,360
  • 1
  • 16
  • 29
  • Thanks Michael. Now that line compiles. However, I have the following as well: JsonArray arrayJson Json = new JsonArray(); arrayJson.add("d", arrayList). Here I am getting the error reason: actual and formal argument lists differ in length. Don't know why ? – Coding Practice Feb 06 '21 at 14:47
  • @CodingPractice - If you can edit your original post and then post your complete class so I can see what you're trying to do that would help. But here is the class definition for a JsonArray and you see exactly what you are allowed to pass into the array. https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/JsonArray.html – Michael Sims Feb 07 '21 at 00:13