Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSON serialization plain array without name

Tags:

json

android

gson

Code of UserRequest class, which contains the list of users.

public class UserRequest {
    private List<User> userList;

    public UserRequest() {
    }

    public UserRequest(List<User> userList) {
        this.userList = userList;
    }

    public List<User> getUserList() {
        return this.userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }

}

Code of User Class, which contains the id, first name and last name of the user.

public class User {

    private String id;
    private String firstName;
    private String lastName;

    public User() {
    }

    public User(String id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

I am using the GSON library, and the issue that I'm having is that my json request when serializing from java objects to json is not formatted in the way I need it to be.

The format of current situation

{"userList":[{"id":"12341234", "firstName": "Joeri", "lastName": "Verlooy"}]}

The format that is desirable:

[{"id":"12341234", "firstName": "Joeri", "lastName": "Verlooy"}]

Is there a way that I can send the plain array of json object without any name?

like image 657
Joeri Verlooy Avatar asked Sep 02 '25 02:09

Joeri Verlooy


2 Answers

try to create a model for items (User) and then convert json to an java ArrayList. assume the json string is in strJson, then you can do it like below:

 ArrayList<User> lstItems = (new Gson()).fromJson(strJson, new TypeToken<ArrayList<User>>() {}.getType());

you dont actually need a model for the list of users (UserRequest), cuz the list doesnt have any name.

if you want to convert an object to a json including a list without a name do like below :

 ArrayList<User> lstUser = new ArrayList<User>();
 lstUser.add(new User());
 (new Gson()).toJson(lstUser, new TypeToken<ArrayList<User>>() {}.getType());
like image 94
Amir Ziarati Avatar answered Sep 04 '25 16:09

Amir Ziarati


To parse "custom" JSON using Gson library you need to use custom TypeAdapter where you'll be able to create list of Users object from unnamed array. Here you have example usage of TypeAdapter.

like image 20
ostojan Avatar answered Sep 04 '25 15:09

ostojan