【问题标题】:Compare two gson converted objects in java比较java中的两个gson转换对象
【发布时间】:2016-01-06 12:25:18
【问题描述】:

我想比较两个Gson转换后的对象的key是否相同。

示例: 我在本地存储的文件 customer.json 中有一个 JSON 对象:

{
  name:"John",
  age:25
}

有一个 API 可以从自定义 volley 请求中提供相同的 JSON 数据,我将其转换为 Customer POJO。

现在我想判断本地存储的JSON数据和从API接收到的JSON数据是否相同。

我正在读取 JSON 文件并将其转换为 Customer,如下所示:

InputStream is = getContext().getResources().openRawResource(
    R.raw.customerjson);
Gson gson = new Gson();
Reader reader = null;
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
Customer customerLocal = gson.fromJson(reader, Customer.class);

现在我拥有两个转换后的 Customer 对象(customerLocalcustomerServer)。

一切正常;问题是我不知道如何比较两个 Gson 转换对象。请注意,我只想比较键(即 POJO 中的变量名,而不是值)。

非常感谢任何帮助。

【问题讨论】:

  • 为什么不比较字符串形式??
  • 我想这个。但是凌空响应会给我转换后的 pojo 而不是字符串。而且,我们正在使用整个项目中的自定义 volley 请求,因此无法更改自定义请求和响应
  • 你所说的pojo是指bean对象吗??
  • 普通的旧 Java 对象 - POJO
  • 简单地遍历 JSON 对象并比较键。 stackoverflow.com/questions/9151619/…

标签: android json gson android-volley


【解决方案1】:

我已经解决了。通过将 gson 转换后的对象转换回 json,如下所示

JSONObject serverJsonObject = new JSONObject(gson.toJson(customerResponse));

然后将 serverJsonObect 与本地存储的 json 对象进行比较 assertJsonEquals 方法来自JsonUnit Library

我的测试用例现在运行良好。

【讨论】:

    猜你喜欢
    • 2012-12-12
    • 2012-04-20
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多