为了账号安全,请及时绑定邮箱和手机立即绑定

java 里面的 Gson 问题

java 里面的 Gson 问题

拉莫斯之舞 2019-03-30 09:33:02
@TestpublicvoidtestGetInt(){Usersusers=usersDAO.get(3);StringjsonUsers=gson.toJson(users);System.out.println("jsonUsers:"+jsonUsers);intavatarId=users.getAvatarId();Avataravatar=avatarDAO.get(avatarId);StringjsonAvatar=gson.toJson(avatar);System.out.println("jsonAvatar:"+jsonAvatar);}打印的数据:jsonUsers:{"user_id":3,"username":"Tony","urlname":"comq"}jsonAvatar:{"id":3,"farm":"farm1","bucket":"hbimg","key":"e925755184a-aSvujx","type":"image/jpeg","width":100,"height":100,"frames":1}怎么把jsonAvatar数据放到jsonUsers里面,变成:{"user_id":3,"username":"Tony","urlname":"comq","avatar":{"id":3,"farm":"farm1","bucket":"hbimg","key":"e925755184a-aSvujx","type":"image/jpeg","width":100,"height":100,"frames":1}}
查看完整描述

2 回答

?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

packagecom;
importcom.google.gson.Gson;
publicclassTestGson{
publicstaticvoidmain(Stringargs[])
{
StringjsonAvatar="";//你的json数据
Useruser=newUser();
user.setUser_id(3);
user.setUsername("Tony");
user.setUrlname("comq");
user.setAvatar(jsonAvatar);
Gsongson=newGson();
Stringresult=gson.toJson(user);
System.out.println(result);
}
}
packagecom;
publicclassUser{
privateintuser_id;
privateStringusername;
privateStringurlname;
privateStringavatar;
publicintgetUser_id(){
returnuser_id;
}
publicvoidsetUser_id(intuser_id){
this.user_id=user_id;
}
publicStringgetUsername(){
returnusername;
}
publicvoidsetUsername(Stringusername){
this.username=username;
}
publicStringgetUrlname(){
returnurlname;
}
publicvoidsetUrlname(Stringurlname){
this.urlname=urlname;
}
publicStringgetAvatar(){
returnavatar;
}
publicvoidsetAvatar(Stringavatar){
this.avatar=avatar;
}
}
                            
查看完整回答
反对 回复 2019-03-30
?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

似乎GSON将对象序列化是一次性的,然后我平时如果遇到这类问题的话
我会这样做
classAvatarUserextendsUsers{
Avataravatar;
}
然后再对AvatarUser进行序列化,这样做的一个好处是方便以后的反序列化。
UPDATE:
新建一个类
UPDATE:
谢谢Dont
publicclassAvatarUserextendsUsers{
publicAvataravatar;
publicAvatarUser(){
}
publicAvatarUser(Usersuser){
setUserId(user.getUserId());
setUserName(user.getUserName());
setUrlName(user.getUrlName());
}
}
@Test
publicvoidtestGetInt(){
Usersuser=usersDAO.get(3);
AvatarUseravatarUser=newAvartarUser(user);
//AvatarUser的getter/setter来自父类Users
//UPDATE直接在子类构造器做好赋值工作,就不用每次都重复编码了@Dont
intavatarId=user.getAvatarId();
Avataravatar=avatarDAO.get(avatarId);
avatarUser.avatar=avatar;
StringjsonAvatar=gson.toJson(avatarUser);
System.out.println("jsonAvatar:"+jsonAvatar);
}
                            
查看完整回答
反对 回复 2019-03-30
  • 2 回答
  • 0 关注
  • 344 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信