Gson解析数值类型时转成double的问题

注册一个解析器就可以,一般只有解析绑定到Object类型才会这样子。

解析器是从ObjectTypeAdapter里面拷贝的代码,做了简单的修改,本来想着集成ObjectTypeAdapter类,但是Gson把这个类标记为final,所以只能做一下修改:

package usermanager;

import com.google.gson.TypeAdapter;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

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

public class TestObjectTypeAdapter extends TypeAdapter<Object> {

    public TestObjectTypeAdapter() {

    }

    @Override
    public void write(JsonWriter out, Object value) throws IOException {
    }

    @Override
    public Object read(JsonReader in) throws IOException {
        JsonToken token = in.peek();

        switch (token) {
            case BEGIN_ARRAY:
                List<Object> list = new ArrayList();
                in.beginArray();

                while (in.hasNext()) {
                    list.add(this.read(in));
                }
                in.endArray();
                return list;
            case BEGIN_OBJECT:
                Map<String, Object> map = new LinkedTreeMap();
                in.beginObject();
                while (in.hasNext()) {
                    map.put(in.nextName(), this.read(in));
                }
                in.endObject();
                return map;
            case STRING:
                return in.nextString();
            case NUMBER:
                String object = in.nextString();
                out(object);
                if (object.contains(".")){
                    return Double.valueOf(object);
                }
                return Double.valueOf(object).longValue();
            case BOOLEAN:
                return in.nextBoolean();
            case NULL:
                in.nextNull();
                return null;
            default:
                throw new IllegalStateException();
        }
    }

    private void out(Object object) {
        System.out.println(object);
    }
}

修改的代码是:

case NUMBER:
    String object = in.nextString();
    out(object);
    if (object.contains(".")){
        return Double.valueOf(object);
    }
    return Double.valueOf(object).longValue();

测试例子:

Map<String, Object> data = null;
gson = new GsonBuilder().registerTypeHierarchyAdapter(Object.class, new TestObjectTypeAdapter()).create();
data = gson.fromJson("{\"data\":200,\"list\":[{\"id\":1,\"name\":\"001\"},{\"id\":2,\"name\":\"002\"},{\"id\":3,\"name\":\"003\"}]}\n", Map.class);

out(data);

解析出来:

{
“data”:200,
“list”:[
{
“id”:1,
“name”:“001”
}
,
{
“id”:2,
“name”:“002”
}
,
{
“id”:3,
“name”:“003”
}

]

}

 

Leave a Comment