简体   繁体   English

通过GSON将类中的成员字段映射转换为JSON

[英]convert member field map in class into JSON by GSON

I have used GSON for a while, and I think it is quite useful! 我已经使用了GSON一段时间了,我认为它非常有用!
Today I encounter a problem, and I think this maybe refer to some advanced usage of GSON . 今天我遇到了一个问题,我想这可能是指GSON一些高级用法。
here is my class definition: 这是我的班级定义:

class ResolvedID
{
    private String type;
    private HashMap<String,String> data=new HashMap<>(4);

    public String getType()
    {
        return this.type;
    }
    public void setType(String type)
    {
        this.type=type;
    }
    public void put(String K, String V)
    {
        this.data.put(K,V);
    }
}

after that I will do the following in some suitable way, here I just write in a simple way: 在那之后我将以一些合适的方式执行以下操作,这里我只是简单地写一下:
I will put some data into this hash map: 我将把一些数据放入这个哈希映射:

ResolvedID id=new ResolvedID();
id.setType("Bachelor");
id.put("school","Computer Science School");
id.put("major","Software Engineering");
id.put("grade","2009");

and I expect GSON might convert it into 我希望GSON可能将其转换为
{"type":"Bachelor", "data":{"school":"Computer Science School", "grade":"2009", "major":"Software Engineering"}}

But unfortunately I only got 但不幸的是我只得到了
{"type":"Bachelor"}}

Can anyone give some direction for these kind of member field container to convert into json by GSON 任何人GSON这类成员字段容器指定一些方向,以便由GSON转换为json

This 这个

A a = new A();
a.data = new HashMap<>();
a.type="teacher";
a.data.put("degree","bachelor");
a.data.put("grade","2013");
Gson gson = new Gson();
System.out.println(gson.toJson(a));

prints 版画

{"type":"teacher","data":{"degree":"bachelor","grade":"2013"}}

for me. 为了我。

You must not be initializing data . 您不能初始化data Gson, by default, will not serialize a field if it is null . 默认情况下,Gson如果为null则不会序列化字段。

It might be easier to use JavaBeans with nested classes. 将JavaBeans与嵌套类一起使用可能更容易。 Here's an example: 这是一个例子:

Note: Obviously you'd build your JsonResponseData class in a different way - I just set prefixed values from within the class for a quick example. 注意:显然你会以不同的方式构建你的JsonResponseData类 - 我只是在类中设置前缀值以获得一个快速示例。

Nested Pojo: 嵌套Pojo:

public class JsonResponseData {

    private JsonResponse mResponse = new JsonResponse();

    public JsonResponse getJsonResponse(){
        return mResponse;
    }

    public void setJsonResponse(JsonResponse mResponse){
        this.mResponse = mResponse;
    }

    private static class JsonResponse {
        private int part = 1;
        private UserData data = new UserData();
    }

    private static class UserData {
        private User user = new User();

        public User getUser(){
            return user;
        }

        public void setUser(User user){
            this.user = user;
        }
    }

    public static class User {
        private String id = "5";
        private String firstName = "User";
        private String lastName = "Name";

        public String getId(){
            return id;
        }

        public void setId(String id){
            this.id = id;
        }

        public String getFirstName(){
            return firstName;
        }

        public void setFirstName(String firstName){
            this.firstName = firstName;
        }

        public String getLastName(){
            return lastName;
        }

        public void setLastName(String lastName){
            this.lastName = lastName;
        }
    }

}

Test Class: 测试类:

public class Test {

    private static Gson gson;
    private static JsonResponseData data;

    public static void main(String[] args){
        gson = new Gson();
        data = new JsonResponseData();

        System.out.print(gson.toJson(data));

    }

}

Output: 输出:

{"mResponse":{"part":1,"data":{"user":{"id":"5","firstName":"User","lastName":"Name"}}}} { “mResponse”:{ “部分”:1, “数据”:{ “用户”:{ “ID”: “5”, “名字”: “用户”, “姓氏”: “姓名”}}}}

I solve this problem at last, it is my problem that I have no getter for this hash map, I think GSON will use reflect the member field. 我终于解决了这个问题,我的问题是我没有这个哈希映射的getter ,我认为GSON会使用反映成员字段。

If member field is public scoped, GSON can get these field and serialize them. 如果成员字段是公共范围的,则GSON可以获取这些字段并对其进行序列化。
If member field is private scoped, GSON will get them by getter , hence GSON could not serialize those private field that have no getter , like my instance above. 如果成员字段是私有作用域, GSON将通过getter获取它们,因此GSON无法序列化那些没有getter私有字段,就像我上面的实例一样。

class ResolvedID
{
    private String type;
    private HashMap<String,String> data=new HashMap<>(4);

    public String getType()
    {
        return this.type;
    }
    public void setType(String type)
    {
        this.type=type;
    }
    //----getter is important for private member field to be reflected by GSON!
    public HashMap getData()
    {
        return this.data;
    }
    public void put(String K, String V)
    {
        this.data.put(K,V);
    }
}

After adding a getter for my class, it is now successfully executed! 为我的班级添加一个getter后,它现在已成功执行! Now I get more comprehension with GSON 's reflection procedure! 现在我对GSON的反射程序GSON更多的理解!

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

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