java 里面的 Gson 问题



 @Test
    public void testGetInt() {
        Users users = usersDAO.get(3);
        String jsonUsers = gson.toJson(users);
        System.out.println("jsonUsers:"+jsonUsers);

        int avatarId = users.getAvatarId();
        Avatar avatar = avatarDAO.get(avatarId);
        String jsonAvatar = 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}}

json java gson

cocoo 10 years, 4 months ago

似乎GSON将对象序列化是一次性的,然后我平时如果遇到这类问题的话
我会这样做


 class AvatarUser extends Users {
  Avatar avatar;
}

然后再对AvatarUser进行序列化,这样做的一个好处是方便以后的反序列化。
UPDATE:
新建一个类
UPDATE:
谢谢Dont


 public class AvatarUser extends Users {
    public  Avatar avatar;
    public AvatarUser() {

    }
    public AvatarUser(Users user) {
     setUserId(user.getUserId());
     setUserName(user.getUserName());
     setUrlName(user.getUrlName());
    }
}

@Test
public void testGetInt() {
    Users user = usersDAO.get(3);
    AvatarUser avatarUser = new AvartarUser(user);
    // AvatarUser的getter/setter 来自父类Users
    // UPDATE 直接在子类构造器做好赋值工作,就不用每次都重复编码了@Dont

    int avatarId = user.getAvatarId();
    Avatar avatar = avatarDAO.get(avatarId);
    avatarUser.avatar = avatar;
    String jsonAvatar = gson.toJson(avatarUser);
    System.out.println("jsonAvatar:"+jsonAvatar);
}

Likey answered 10 years, 4 months ago


 package com;

import com.google.gson.Gson;

public class TestGson {

public static void main(String args[])
{

    String jsonAvatar=""; //你的json数据
    User user=new User();
    user.setUser_id(3);
    user.setUsername("Tony");
    user.setUrlname("comq");
    user.setAvatar(jsonAvatar);
    Gson gson=new Gson();
    String result=gson.toJson(user);
    System.out.println(result);
 }

}


package com;

public class User {

private int user_id;

private String username;

private String urlname;

private String avatar; 

public int getUser_id() {
    return user_id;
}

public void setUser_id(int user_id) {
    this.user_id = user_id;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getUrlname() {
    return urlname;
}

public void setUrlname(String urlname) {
    this.urlname = urlname;
}

public String getAvatar() {
    return avatar;
}

public void setAvatar(String avatar) {
    this.avatar = avatar;
}
}

小黑炮 answered 10 years, 4 months ago

Your Answer