java 使用 Gson 将 JSON 映射到 POJO
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27039511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mapping JSON into POJO using Gson
提问by Mulgard
I have the following JSON to represent the server response for a salt request:
我有以下 JSON 来表示盐请求的服务器响应:
{
"USER":
{
"E_MAIL":"email",
"SALT":"salt"
},
"CODE":"010"
}
And i tried to map it with the following POJO:
我尝试使用以下 POJO 映射它:
public class SaltPOJO {
private String code = null;
private User user = null;
@Override
public String toString() {
return this.user.toString();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public class User {
private String e_mail = null;
private String salt = null;
@Override
public String toString() {
return this.e_mail + ": " + this.salt;
}
public String getE_mail() {
return e_mail;
}
public void setE_mail(String e_mail) {
this.e_mail = e_mail;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
}
}
Now everytime i do this:
现在每次我这样做:
Gson gson = new Gson();
SaltPOJO saltPojo = gson.fromJson(json.toString(), SaltPOJO.class);
Log.v("Bla", saltPojo.toString());
The saltPojo.toString()
is null. How can i map my JSON into POJO using Gson?
Is the order of my variables important for the Gson mapping?
该saltPojo.toString()
为空。如何使用 Gson 将我的 JSON 映射到 POJO?我的变量顺序对 Gson 映射重要吗?
回答by Braj
Is the order of my variables important for the Gson mapping?
我的变量顺序对 Gson 映射重要吗?
No, that's not the case.
不,事实并非如此。
How can i map my JSON into POJO using Gson?
如何使用 Gson 将我的 JSON 映射到 POJO?
It's Case Sensitiveand the keys in JSON string should be same as variable names used in POJO class.
它区分大小写,JSON 字符串中的键应与 POJO 类中使用的变量名称相同。
You can use @SerializedNameannotation to use any variable name as your like.
您可以使用@SerializedName注释来随意使用任何变量名称。
Sample code:
示例代码:
class SaltPOJO {
@SerializedName("CODE")
private String code = null;
@SerializedName("USER")
private User user = null;
...
class User {
@SerializedName("E_MAIL")
private String e_mail = null;
@SerializedName("SALT")
private String salt = null;
回答by SMA
You don't have proper mapping between your getter and setter. If you change your json to something like below, it would work:
你的 getter 和 setter 之间没有正确的映射。如果您将 json 更改为如下所示的内容,它将起作用:
{
"user":
{
"email":"email",
"salt":"salt"
},
"code":"010"
}
If you are getting json form third party then unfortunately, you would have to change your pojo or you could use adapter.
如果您从第三方获取 json 格式,那么不幸的是,您将不得不更改您的 pojo 或者您可以使用适配器。