How to use Gson to serialize objects in android?

a 夏天 提交于 2019-11-28 12:29:15

gson can be used with Java on any platform – not only Android.

Using gson to serialize a single object:

    // Serialize a single object.    
    public String serializeToJson(MyClass myClass) {
        Gson gson = new Gson();
        String j = gson.toJson(myClass);
        return j;
    }

Using gson to deserialize to a single object.

    // Deserialize to single object.
    public MyClass deserializeFromJson(String jsonString) {
        Gson gson = new Gson();
        MyClass myClass = gson.fromJson(jsonString, MyClass.class);
        return myClass;
    }

As you can see from the examples, gson is quite magical :) It is not actually magical - you need to ensure at least a couple of things:

Ensure that your class has a no args constructor so that the gson library can easily get an instance.

Ensure that the attribute names match those in the json so that the gson library can map fields from the json to the fields in your class.

Also see https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!