以Gerenic方式处理JSON响应

时间:2015-03-24 08:40:42

标签: java arrays json

我有两个不同的请求生成的两个不同的Json响应(具有不同的键):

回复1:

{
    "response": {
        "count": 2,
        "programs": [
            {
                "title": "xyz1",
                "desc": "ABCDEF1"
            },
            {
                "title": "xyz2",
                "desc": "ABCDEF2"
            }
        ]
    }
}

回复2

{
    "response": {
        "count": 3,
        "shows": [
            {
                "name": "PQR1",
                "desc": "qwerty1"
            },
            {
                "name": "PQR2",
                "desc": "qwerty2"
            },
            {
                "name": "PQR3",
                "desc": "qwerty3"
            }
        ]
    }
}

我们可以看到回复包含具有不同键的数据。但最终它可以转换为(Array)相同的Java对象,如下所示:

Program {
   String title;
   int description;
}

我想编写单个解析逻辑来处理不同的键名并返回程序列表。如何有效地实现这一目标?

是否有可以方便地执行此操作的库?

1 个答案:

答案 0 :(得分:3)

您可以在对两者进行反序列化时选择getter中的字段(示例适用于GSON):

class Program {
    private String title, name;
    @SerializedName("desc") private String description;

    private String getTitle() {
        return title == null ? name : title;
    }

    // other getters, empty constructor and so on...
}

另外(再次GSON),您可以在创建TypeAdapter对象时注册自己的Gson

// let Program have empty constructor (or no constructors at all), getters and setters
class ProgramAdapter extends TypeAdapter<Program> {

    @Override
    public Program read(final JsonReader in) throws IOException {
        final Program obj = new Program();

        in.beginObject();
        while (in.hasNext()) {
            String jsonTag = in.nextName();
            if ("desc".equals(jsonTag)) {
                obj.setDescription(in.nextString());
            } else if ("title".equals(jsonTag) 
                    || "name".equals(jsonTag)) {
                obj.setTitle(in.nextString());
            }
        }
        in.endObject();

        return obj;
    }

    @Override
    public void write(final JsonWriter out, final Program obj)
            throws IOException {
        out.beginObject();
        out.name("title").value(obj.getTitle());
        out.name("desc").value(obj.getDescription());
        out.endObject();
    }
}

// then, when create `Gson` object:

Gson gson = new GsonBuilder().registerTypeAdapter(Program.class, new ProgramAdapter()).create();