Gson解析数据有时是字符串而有时是对象

时间:2012-07-31 14:06:34

标签: android deserialization gson

我必须解析一个有时看起来像

的json

school_name:“马丁高中”, 领导: {     first_name:“奥斯汀”,     last_name:“万豪”, }

有时候是

school_name:“马丁高中”, 领导:“/ leader / 3434”。

我试图看看是否有一个示例反序列化器可以处理“领导者”某些字符串,有时候是一个对象。但找不到任何。

这可以用gson吗?

1 个答案:

答案 0 :(得分:2)

您只需为TypeAdapter实施Leader即可。在read(JsonReader in)中使用JsonReader.peek()查看即将发生的内容,然后阅读并将其转换为Leader。它应该是相当微不足道的。

我做了一个练习......

public class GsonStringOrObjectDemo {
    @EqualsAndHashCode
    private static class Leader {
        String firstName;
        String lastName;
    }
    private static class LeaderAdapter extends TypeAdapter<Leader> {
        @Override
        public void write(JsonWriter out, Leader value) throws IOException {
            if (useString) {
                out.value(value.firstName + ":" + value.lastName);
            } else {
                out.beginObject();
                out.name("firstName");
                out.value(value.firstName);
                out.name("lastName");
                out.value(value.lastName);
                out.endObject();
            }
            useString = !useString;
        }

        @Override
        public Leader read(JsonReader in) throws IOException {
            final Leader result = new Leader();
            final JsonToken type = in.peek();
            switch (type) {
            case BEGIN_OBJECT:
                in.beginObject();
                while (true) {
                    final String key = in.nextName();
                    final String value = in.nextString();
                    if (key.equals("firstName")) result.firstName = value;
                    else if (key.equals("lastName")) result.lastName = value;
                    else throw new JsonParseException("Unexpected key in Leader: " + key);
                    if (in.peek() == JsonToken.END_OBJECT) break;
                }
                in.endObject();
                return result;
            case STRING:
                final String string = in.nextString();
                final int pos = string.indexOf(':');
                result.firstName = string.substring(0, pos);
                result.lastName = string.substring(pos+1);
                return result;
            default:
                throw new JsonParseException("Expected string or object for Leader, got: " + type);
            }
        }

        private boolean useString;
    }

    public static void main(String[] args) throws Exception {
        final Gson gson = new GsonBuilder().registerTypeAdapter(Leader.class, new LeaderAdapter()).setPrettyPrinting().create();
        final Leader[] leaders = new Leader[10];
        for (int i=0; i<leaders.length; ++i) {
            leaders[i] = new Leader();
            leaders[i].firstName = "First" + i;
            leaders[i].lastName = "Last" + i;
        }
        final String json = gson.toJson(leaders);
        final Leader[] leaders2 = gson.fromJson(json, Leader[].class);
        Assert.assertTrue(Arrays.equals(leaders, leaders2));
    }
}