比较 java 中的两个 gson 转换对象

Compare two gson converted objects in java

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

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

{
  name:"John",
  age:25
}

有一个 API 从我正在转换为 Customer POJO 的自定义截击请求中提供相同的 JSON 数据。

现在想判断本地存储的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 中的变量名,而不是值)。

非常感谢任何帮助。

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

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

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

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