Marco
Marco

Reputation: 707

Parse a JSON string to a custom class

In an app that I'm developing I receive from a web-service a JSON string, I'm trying to covert this string into a custom class like:

public class User {
public String userID;
public String description;
public int PIN;

public User(){}
}

whith it's getter and setter method.

I've tried to do that stuff using a Gson and the method:

Gson gson = new Gson();
User user = gson.fromJson(String fromServer, User.class);

where the String "fromServer" it's already codified in JSON

if i print the String fromServer in a TextView i have an output like

[{"userId":"admin","description":"administrator","PIN":"00001"}]

but when i call

user.getUserId();

I got a NullPointerException and I don't Know why

Upvotes: 0

Views: 1787

Answers (3)

sddamico
sddamico

Reputation: 2130

Your server is returning an array of Users. Try using Gson like this:

Type listType = new TypeToken<ArrayList<User>>() {}.getType();
List<User> users = gson.fromJson(fromServer, listType);
User user = users.get(0);

Upvotes: 1

SohailAziz
SohailAziz

Reputation: 8034

Answer above is correct. You can verify this by creating User class using Json2Pojo and then using Gson to convert the json to class. Your User class should look like:

public class User {

private String userId;
private String description;
private String PIN;

public String getUserId() {
return userId;
}


public void setUserId(String userId) {
this.userId = userId;
}


public String getDescription() {
return description;
}


public void setDescription(String description) {
this.description = description;
}

public String getPIN() {
return PIN;
}

public void setPIN(String PIN) {
this.PIN = PIN;
}

}

Now you can use Gson to convert json to User.

Gson gson = new Gson();
User user = gson.fromJson(fromServer, User.class)

Upvotes: 0

Albin
Albin

Reputation: 4220

Case sensitivity. userID in java and userId in json.

Upvotes: 0

Related Questions