18

I have a json like this:

[
  [
    "Passport Number",
    "NATIONALITY",
    "REASONS"
  ],
  [
    "SHAIS100",
    "INDIA",
    ""
  ],
  [
    "",
    "",
    "Agent ID is not matched."
  ],
  [
    "",
    "",
    ""
  ]
]

I want to populate this to ArrayList<String[]>,Please tell me how to do?

And empty strings should not convert as null.

MikO
  • 18,243
  • 12
  • 77
  • 109
  • https://stackoverflow.com/a/55691694/470749 was helpful for me. `list.add(item.getAsString());` – Ryan Mar 22 '21 at 16:15

2 Answers2

54

That's very simple, you just need to do the following:

1.- First create the Gson object:

Gson gson = new Gson();

2.- Then get the correspondent Type for your List<String[]> (Note that you can't do something like List<String[]>.class due to Java's type erasure):

Type type = new TypeToken<List<String[]>>() {}.getType();

3.- Finally parse the JSON into a structure of type type:

List<String[]> yourList = gson.fromJson(yourJsonString, type);
MikO
  • 18,243
  • 12
  • 77
  • 109
  • Type type = new TypeToken>() {}.getType(); it should be Type type = new TypeToken>() {}.getType(); similarly List yourList = gson.fromJson(yourJsonString, type); it should be List yourList = gson.fromJson(yourJsonString, type); – user2162130 Jul 07 '21 at 07:21
17

Take a look at Gson docs

Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};

(Serialization)
gson.toJson(ints);     ==> prints [1,2,3,4,5]
gson.toJson(strings);  ==> prints ["abc", "def", "ghi"]

(Deserialization)
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); 
==> ints2 will be same as ints

Tis is important for you: We also support multi-dimensional arrays, with arbitrarily complex element types

For null objects, Gson by default will not convert as null. Ref. But you can configure to scan those nulls attributes if you want to do it after.

The default behaviour that is implemented in Gson is that null object fields are ignored. This allows for a more compact output format; however, the client must define a default value for these fields as the JSON format is converted back into its Java.

Here's how you would configure a Gson instance to output null:

Gson gson = new GsonBuilder().serializeNulls().create();

In your problem maybe you don't need to configure that.

I hope it helps.

Deividi Cavarzan
  • 10,034
  • 13
  • 66
  • 80