用于使用数字键解析javaScript对象的java库

时间:2012-03-15 08:20:25

标签: javascript json key numeric

我在解析从Web服务器收到的javaScript对象时遇到了一些问题。 这些对象应该是JSON但包含数字键。

javaScript对象:

{a: "alpha", 2: "two"}   

问题是如何在java中解码这样的javascript对象? 是否有可以使用的现有库?如果有如何在java中表示该对象:

public class JavaObject {
   private String a;           // for field - a: "alpha"
   private ???                 // for field - 2: "two"
}

由于

1 个答案:

答案 0 :(得分:2)

由于我没有在网上找到任何解决我问题的方法,我自己实现了GSON库的适配器来处理这些数据。

众所周知,JSON仅支持字符串键。 如果一个像这样的json数据 {“a”:“alpha”,“2”:“two”,“3”:3} 我可以在普通的JSONObject中转换它,但仍然是不能将它转换为我自己的java对象。 为了处理这种情况,我创建了一个ObjectMap对象

// ObjectMap.java
import java.util.Map;

public class ObjectMap<V> {

    private Map<String, V> map;

    public ObjectMap(Map<String, V> map) {
        setMap(map);
    }

    public Map<String, V> getMap() {
        return map;
    }

    public void setMap(Map<String, V> map) {
        this.map = map;
    }

    @Override
    public String toString() {
        return "ObjectMap [map=" + map + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((map == null) ? 0 : map.hashCode());
        return result;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ObjectMap other = (ObjectMap) obj;
        if (map == null) {
            if (other.map != null)
                return false;
        } else if (!map.equals(other.map))
            return false;
        return true;
    }
}

和它的一个gson适配器ObjectMapAdapter。

//ObjectMapAdapter.java
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.$Gson$Types;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

public class ObjectMapAdapter<V> extends TypeAdapter<ObjectMap<V>> {

    public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public <T> TypeAdapter create(Gson gson, TypeToken<T> typeToken) {

            Type type = typeToken.getType();
            Class<? super T> rawType = typeToken.getRawType();

            if (!ObjectMap.class.isAssignableFrom(rawType)) {
                return null;
            }

            // if (rawType != ObjectMap.class) {
            // return null;
            // }

            Type componentType;
            if (type instanceof ParameterizedType) {
                componentType = ((ParameterizedType) type).getActualTypeArguments()[0];
            } else {
                componentType = Object.class;
            }

            TypeAdapter<?> componentTypeAdapter = gson.getAdapter(TypeToken.get(componentType));
            return new ObjectMapAdapter(gson, componentTypeAdapter, $Gson$Types.getRawType(componentType));

        }
    };

    // private final Class<V> valueType;
    private final TypeAdapter<V> valueTypeAdapter;

    public ObjectMapAdapter(Gson context, TypeAdapter<V> componentTypeAdapter, Class<V> componentType) {
        this.valueTypeAdapter = new TypeAdapterRuntimeTypeWrapper<V>(context, componentTypeAdapter, componentType);
        // this.valueType = componentType;
    }

    public ObjectMap<V> read(JsonReader in) throws IOException {

        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }

        Map<String, V> map = new LinkedHashMap<String, V>();
        in.beginObject();
        while (in.hasNext()) {
            String key = in.nextName();
            V comp = valueTypeAdapter.read(in);
            map.put(key, comp);
        }
        in.endObject();

        return new ObjectMap<V>(map);
    }

    @Override
    public void write(JsonWriter out, ObjectMap<V> map) throws IOException {
        if (map == null) {
            out.nullValue();
            return;
        }

        out.beginObject();
        for (Entry<String, V> entry : map.getMap().entrySet()) {
            out.name(entry.getKey());
            valueTypeAdapter.write(out, entry.getValue());
        }
        out.endObject();
    }
}

创建自定义GSON构建器并注册此工厂

gsonBuilder.registerTypeAdapterFactory(ObjectMapAdapter.FACTORY);

您已准备好解码此类数据

{"a": "alpha", "2": "two", "3":3}

进入地图

ObjectMap [map={a=alpha, 2=two, 3=3}]
相关问题