小编Ari*_*ise的帖子

自定义序列化程序 - 使用GSON的反序列化程序,用于BasicNameValuePairs列表

我正在尝试为一些BasicNameValuePair对象列表实现自定义gson序列化器/解串器.

我在这里看到了部分解决方案代码(用于序列化): 如何让Gson序列化基本名称值对列表?

但是我想实现反序列化,我尝试了机会,代码在这里:

package dto;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;


import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;


    public class KeyValuePairSerializer extends TypeAdapter<List<BasicNameValuePair>> {
        @Override
        public void write(JsonWriter out, List<BasicNameValuePair> data) throws IOException {
            out.beginObject();
            for(int i=0; i<data.size();i++){
                out.name(data.get(i).getName());
                out.value(data.get(i).getValue());
            }
            out.endObject();
        }

        @Override
        public List<BasicNameValuePair> read(JsonReader in) throws IOException {
            ArrayList<BasicNameValuePair> list=new ArrayList<BasicNameValuePair>();
             in.beginObject();
             while (in.hasNext()) {
               String key = in.nextName();
               String value = in.nextString();
               list.add(new BasicNameValuePair(key,value));
             }  
             in.endObject();   
             return list;
        }

}
Run Code Online (Sandbox Code Playgroud)

用于初始化和填充列表的代码

ArrayList<BasicNameValuePair> …
Run Code Online (Sandbox Code Playgroud)

serialization android json key-value gson

8
推荐指数
1
解决办法
9137
查看次数

标签 统计

android ×1

gson ×1

json ×1

key-value ×1

serialization ×1