简体   繁体   中英

GSON - JSON to Java object

I have been applying my expert level googling skills to no avail, so Stackoverflow I need your assistance.

I want to convert my json object to a java object in java.

JSON object appears as... - {"password":"b","userName":"a"}

and the print statements once i 'attempt' to convert it are... username = b password = null

my question is why is this happening and how can i solve the issue? (Code follows)

    Gson gson = new Gson();
    JSONObject jObj = new JSONObject(request.getParameter("input")); 
    User user = gson.fromJson(jObj.toString(), User.class);

    System.out.println(user.getPassword());
    System.out.println(user.getUsername());

and the 'model' class....

public class User {
private String username;
private String password;

public User(String uName, String pWord){
    this.username = uName;
    this.password = pWord;
}

public void setUsername(String uName){
    username = uName;
}

public String getUsername(){
    return username;
}

public void setPassword(String pWord){
    password = pWord;
}

public String getPassword(){
    return password;
}
}

The solution in this case was was related to the mapping in the JSON as 'userName' when it should have been 'username'

refer to the comments for additional information.

hopefully other users find this a useful resource.

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