简体   繁体   English

GSON-JSON到Java对象

[英]GSON - JSON to Java object

I have been applying my expert level googling skills to no avail, so Stackoverflow I need your assistance. 我一直没有使用我的专家级谷歌搜索技能,因此Stackoverflow我需要您的帮助。

I want to convert my json object to a java object in java. 我想将json对象转换为java中的java对象。

JSON object appears as... - {"password":"b","userName":"a"} JSON对象显示为...-{“密码”:“ b”,“用户名”:“ a”}

and the print statements once i 'attempt' to convert it are... username = b password = null 我“尝试”进行转换后的打印语句是...用户名= b密码= 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' 这种情况下的解决方案与JSON中作为“ userName”的映射有关,而应该是“ username”

refer to the comments for additional information. 请参阅注释以获取更多信息。

hopefully other users find this a useful resource. 希望其他用户可以找到有用的资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM