美文网首页
使用枚举类型做为 javabean

使用枚举类型做为 javabean

作者: 李云龙_ | 来源:发表于2020-11-17 14:52 被阅读0次

使用枚举类型做为 javabean

接口返回的 json 中状态一般是 Int 类型的,如果不使用枚举则在代码中不知道这个 Int 是什么具体类型,使用枚举也不会耗费多少性能。

1. json 格式
{
    "box":{
        "name":"hat",
        "price":200,
        status : 2
    }
}
2. 枚举变量
enum class BoxStatusType(val status: Int) {
    S_NEW(0),
    S_SHOW(1),
    S_ACTIVE(2),
    S_END(3);

    companion object {
        fun buildStatus(s: Int): BoxStatusType? {
            for (status in BoxStatusType.values()) {
                if (s == status.status) {
                    return status
                }
            }
            return null
        }
    }
}
3. javaBean
open class Box {
    var name: String = ""
    var price: Int = 0
    var status: BoxStatusType? = null
}
4. 自定义 JsonSerializer
class BoxStatusTypeSerializer : JsonSerializer<BoxStatusType>, JsonDeserializer<BoxStatusType> {
    override fun serialize(src: BoxStatusType?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
        return JsonPrimitive(src?.status)
    }

    override fun deserialize(json: JsonElement, typeOfT: Type?, context: JsonDeserializationContext?): BoxStatusType? {
        return BoxStatusType.buildStatus(json?.asInt)
    }

}
5. 注册自定义的 JsonSerializer
    private static Retrofit getRetrofitInstance() {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(BoxStatusType.class, new BoxStatusTypeSerializer())
                .create();
        if (mRetrofit == null) {
            synchronized (HTTPCenter.class) {
                if (mRetrofit == null) {
                    mRetrofit = new Retrofit.Builder()
                            .baseUrl(HTTPService.Companion.getSERVICE_DEFAULT())
                            .addConverterFactory(GsonConverterFactory.create(gson))
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .client(initOkHttpClient()).build();
                }
            }
        }
        return mRetrofit;
    }

相关文章

  • 使用枚举类型做为 javabean

    使用枚举类型做为 javabean 接口返回的 json 中状态一般是 Int 类型的,如果不使用枚举则在代码中不...

  • Swift 基础笔记 - 枚举

    枚举 OC定义和使用枚举 Swift定义枚举类型 Swift判断枚举类型 枚举成员类型

  • TS学习笔记(6)-枚举类型

    枚举类型 ========= 知识点 枚举类型的定义方法 枚举类型的使用方法 代码

  • SpringBoot 入门笔记(七)自定义枚举类型

    定义枚举类 在抛出异常中使用枚举类型 异常处理类中接受枚举类型

  • 每日一问17——swift基础(03)

    枚举类型 swift中使用enum关键字声明枚举。并且可以指定枚举的类型 方式一、 方式一枚举类型甚至可以为Str...

  • 枚举类型使用

    废话不多说,直接来干货 字符串枚举 数字枚举 默认从0开始,如果设置Red = 1,则从1开始依次递增 场景 1,...

  • C#枚举类型概述(一)

    枚举类型概述 枚举类型使用 enum 关键字声明。是值类型,但不能定义任何方法、属性、事件。(PS. 可以使用“扩...

  • Swift枚举和结构体(三)

    1. 枚举, 使用enum来创建枚举, 类似于类的命名类型, 枚举类型赋值可以是字符串/字符/整形/浮点型, 枚举...

  • 01.C语言中的枚举类型

    枚举类型 c语言中,如果想表示符号常亮而不是字面值,除了#define...外,还可以使用枚举类型枚举类型的定义

  • TypeScript在Vue中的使用

    基础 1,类型 除了上面的常见的基本类型意外,还可以通过接口(interface)定义对象类型 2,枚举 使用枚举...

网友评论

      本文标题:使用枚举类型做为 javabean

      本文链接:https://www.haomeiwen.com/subject/ifixiktx.html