在Android中解释服务器数据


前言

在这一篇文章中,主要讲一下如何使用Gson解释服务器返回的具有固定格式的数据。

分析

服务器:在本地使用nodejs的express框架建立的简单服务器。它返回了的数据如下:

var testArrayStr = "{\"data\": [{\"cnName\": \"jakewharton\",\"age\": 13,\"IsBoy\": true}, {\"cnName\": \"小红\",\"age\": 24,\"IsBoy\": false}],\"msg\": \"\",\"status\": 200}";

var testObjStr = "{\"data\": {\"cnName\": \"小红\",\"age\": 24,\"IsBoy\": false},\"msg\": \"\",\"status\": 200}";

res.end(testObjStr);

我们可以和服务器约定返回的格式模版如下,他们的主要区别是data,可以是对象或者对象的数组形式。

定义解释data为对象的模板:

public class BaseObjectResult<T> {
    public T data;
    public String msg;
    public int status;
}

定义解释data为数组的模版:

public class BaseArrayResult<T> {
    public List<T> data;
    public String msg;
    public int status;
}

实体对象:
TestData.java

public class TestData {
    public String cnName;
    public int age;
    public boolean IsBoy;

    @Override
    public String toString() {
        return "testData:" +
                "cnName=" + this.cnName + " " +
                "age=" + this.age + " " +
                "IsBogy=" + this.IsBoy;
    }
}

使用retrofit和gson解释

自定义Converter.Factory

public class DecodeConverterFactory extends Converter.Factory {

    public static DecodeConverterFactory create() {
        return create(new Gson());
    }

    public static DecodeConverterFactory create(Gson gson) {
        return new DecodeConverterFactory(gson);
    }

    private final Gson gson;

    private DecodeConverterFactory(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        this.gson = gson;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new CustomResponseBodyConverter<>(adapter, type);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new DecodeRequestBodyConverter<>(gson, adapter);
    }

}

CustomResponseBodyConverter.java

public class CustomResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final TypeAdapter<T> adapter;
    private Type mType;

    public CustomResponseBodyConverter(TypeAdapter<T> adapter, Type type) {
        this.adapter = adapter;
        this.mType = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        //解密字符串
        if(mType == String.class) {
            return (T) value.string();
        } else {
            
        }
    }
}

DecodeRequestBodyConverter.java

public class DecodeRequestBodyConverter<T> implements Converter<T, RequestBody> {

    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
    private static final Charset UTF_8 = Charset.forName("UTF-8");

    private final Gson gson;
    private final TypeAdapter<T> adapter;
    DecodeRequestBodyConverter(Gson gson,TypeAdapter<T> adapter){
        this.gson = gson;
        this.adapter = adapter;
    }
    @Override
    public RequestBody convert(T value) throws IOException {
        Buffer buffer = new Buffer(); //value.toString()
        Writer writer = new OutputStreamWriter(buffer.outputStream(),UTF_8);
        JsonWriter jsonWriter = gson.newJsonWriter(writer);
        adapter.write(jsonWriter,value);
        jsonWriter.flush();
        return RequestBody.create(MEDIA_TYPE,buffer.readByteString());
    }

}

开始使用:

TestDataApi.java

public interface TestDataApi {
    @GET("/")
    Call<BaseObjectResult<TestData>> getArrayData();
}
当data为对象时:
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.20.168:3000")
                .addConverterFactory(DecodeConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        TestDataApi testDataApi = retrofit.create(TestDataApi.class);
        Call<BaseObjectResult<TestData>> resultCall = testDataApi.getArrayData();
        resultCall.enqueue(new Callback<BaseObjectResult<TestData>>() {
            @Override
            public void onResponse(Call<BaseObjectResult<TestData>> call, Response<BaseObjectResult<TestData>> response) {
                if(response.isSuccessful()) {
                    if(response.body() != null) {
                        TestData testData = response.body().data;
                        Log.d("hyj", "msg=" +  response.body().msg + "  "
                                + "status=" + response.body().status + "  "
                                + testData.toString());
                    }
                }

            }

            @Override
            public void onFailure(Call<BaseObjectResult<TestData>> call, Throwable t) {
                ToastUtil.showShort(mContext, t.getMessage());
            }
        });

输出的结果是:

04-08 16:04:56.053 31894-31894/com.zhangsunyucong.chanxa.testproject D/hyj: msg= status=200 testData:cnName=小红 age=24 IsBogy=false

当data为数组时:
Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.20.168:3000")
                .addConverterFactory(DecodeConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        TestDataApi testDataApi = retrofit.create(TestDataApi.class);
        Call<BaseArrayResult<TestData>> resultCall = testDataApi.getArrayData();
        resultCall.enqueue(new Callback<BaseArrayResult<TestData>>() {
            @Override
            public void onResponse(Call<BaseArrayResult<TestData>> call, Response<BaseArrayResult<TestData>> response) {
                if(response.isSuccessful()) {
                    if(response.body() != null) {
                        List<TestData> testData = response.body().data;
                        if(testData != null) {
                            for(int i = 0; i < testData.size(); i++) {
                                Log.d("hyj", "msg=" +  response.body().msg + "  "
                                        + "status=" + response.body().status + "  "
                                        + testData.get(i).toString());
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseArrayResult<TestData>> call, Throwable t) {
                ToastUtil.showShort(mContext, t.getMessage());
            }
        });

输出的结果是:

04-08 16:11:44.703 32440-32440/com.zhangsunyucong.chanxa.testproject D/hyj: msg= status=200 testData:cnName=jakewharton age=13 IsBogy=true
04-08 16:11:44.703 32440-32440/com.zhangsunyucong.chanxa.testproject D/hyj: msg= status=200 testData:cnName=小红 age=24 IsBogy=false

手动解释####

关键的代码是:

    private ParameterizedType type(final Class raw, final Type... args) {
        return new ParameterizedType() {
            public Type getRawType() {
                return raw;
            }

            public Type[] getActualTypeArguments() {
                return args;
            }

            public Type getOwnerType() {
                return null;
            }
        };
    }

当data返回的是对象时:

TestDataApi testDataApi = retrofit.create(TestDataApi.class);
        Call<String> resultCall = testDataApi.getArrayData();
        resultCall.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if(response.isSuccessful()) {
                    if(response.body() != null) {
                        String testDataStr = response.body();
                        Gson gson = new Gson();

                        BaseObjectResult<TestData> testData = gson.fromJson(testDataStr,
                                type(BaseObjectResult.class, TestData.class));

                        Log.d("hyj", "msg=" +  testData.msg + "  "
                                + "status=" + testData.status + "  "
                                + testData.data.toString());
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                ToastUtil.showShort(mContext, t.getMessage());
            }
        });

当返回的data是数组时:

TestDataApi testDataApi = retrofit.create(TestDataApi.class);
        Call<String> resultCall = testDataApi.getArrayData();
        resultCall.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if(response.isSuccessful()) {
                    if(response.body() != null) {
                        String testDataStr = response.body();
                        Gson gson = new Gson();

                        BaseArrayResult<TestData> testData = gson.fromJson(testDataStr,
                                type(BaseArrayResult.class, TestData.class));

                        if(testData != null && testData.data != null) {
                            for(int i = 0; i < testData.data.size(); i++) {
                                Log.d("hyj", "msg=" +  testData.msg + "  "
                                        + "status=" + testData.status + "  "
                                        + testData.data.get(i).toString());
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                ToastUtil.showShort(mContext, t.getMessage());
            }
        });

它们返回的结果和第一种方法的返回结果是一样的。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,175评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,674评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,151评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,597评论 1 269
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,505评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,969评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,455评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,118评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,227评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,213评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,214评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,928评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,512评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,616评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,848评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,228评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,772评论 2 339

推荐阅读更多精彩内容

  • Scala与Java的关系 Scala与Java的关系是非常紧密的!! 因为Scala是基于Java虚拟机,也就是...
    灯火gg阅读 3,404评论 1 24
  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 3,199评论 0 4
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,555评论 18 139
  • 《ilua》速成开发手册3.0 官方用户交流:iApp开发交流(1) 239547050iApp开发交流(2) 1...
    叶染柒丶阅读 10,412评论 0 11
  • 灼日裂天云,凉风上我身。 但闻蝉语噪,不作此间人。 仄起首句押韵,五绝,中华新韵
    迷曳阅读 128评论 3 7