Reputation: 613
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?
Upvotes: 4
Views: 4647
Reputation: 15097
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());
Upvotes: 2
Reputation: 775
JSONArray jsonArray = new JSONArray();
for (int i=0;i<userList.size();i++) {
jsonArray.add(userList.get(i));
}
userList will be your list of users and here jsonArray will have the desirable format
Upvotes: 0