简体   繁体   中英

How to convert string array to object using GSON/ JSON?

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM