我想比较两个Gson转换对象的key是否相同
例子: 我在本地存储的 customer.json 文件中有一个 JSON 对象:
{
name:"John",
age:25
}
有一个 API 可以从我正在转换为 Customer
POJO 的自定义 volley 请求中提供相同的 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
对象(customerLocal
和 customerServer
)。
一切正常;问题是我不知道如何比较两个 Gson 转换后的对象。请注意,我只想比较键(即 POJO 中的变量名,而不是值)。
非常感谢任何帮助。
最佳答案
我已经解决了。通过将 gson 转换后的对象转换回 json,如下所示
JSONObject serverJsonObject = new JSONObject(gson.toJson(customerResponse));
然后将 serverJsonObect 与本地存储的 json 对象进行比较 assertJsonEquals 方法来自 JsonUnit Library
我的测试用例现在运行良好。
关于android - 比较java中的两个gson转换对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34633122/