继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Gson 的@Expose 注解 和 @SerializedName 注解

米脂
关注TA
已关注
手记 492
粉丝 88
获赞 590

2017年7月7日 见Gson 的@Expose 注解 和 @SerializedName 注解  查阅资料后 记录:

@Expost注解的作用:区分实体中不想被序列化的属性,包含俩个属性-deserialize(反序列化) 和 serialize(序列化) 默认true

使用new GsonBuilder().excludeFiedlsWithoutExpostAnnotaion().create();创建Gson对象,没有@Wxpose注释的属性讲不会被序列化.

@SerializedName 注解的作用:定义属性序列化后的名称;

下面是代码案例:

采用Gson studio 需添加依赖: (最好为版本较新的)

compile 'com.google.code.gson:gson:2.6.2'
package ....;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.io.Serializable;

/**
 * Created by john on 2017/7/7.
 */

public class User implements Serializable {

    private Long id;
    @Expose
    private int age;
    @Expose
    @SerializedName("username")
    private String name;

    public User(Long id, int age, String name){
        this.id = id;
        this.age = age;
        this.name = name;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}package com.example.dyf.dyfdemo.gson;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Created by john on 2017/7/7.
 */

public class GsonActivity extends Activity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //
        testGson();
    }


    private void testGson(){
        //gson的@Expose注解和@SerializedName注解
        User user = new User(1L, 17, "Jion");
        //使用 new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        //创建Gson对象,没有@Expose注释的属性将不会被序列化
        Gson g1 = new Gson();
        //使用 new Gson();
        System.out.println(g1.toJson(user));// {"age":17,"id":1,"username":"Jion"}
        //使用 new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        Gson g2 = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        System.out.println(g2.toJson(user));  // {"age":17,"username":"Jion"}

    }

}

原文链接:http://www.apkbus.com/blog-535369-68223.html

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP

热门评论

过滤某个字算用个注解呢?

查看全部评论