Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 857
Phani Kumar Bhavirisetty Avatar asked Jul 31 '13 12:07

Phani Kumar Bhavirisetty


People also ask

How do you convert a string to a JSON object in Python?

Use the json.loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary. This process is called deserialization – the act of converting a string to an object.

How do I convert a JSON object to a string?

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

What does GSON toJSON do?

Gson is a Java library that can be used to convert Java objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

Is GSON better than JSON?

GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.


1 Answers

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);
like image 170
MikO Avatar answered Sep 29 '22 02:09

MikO