英文:
How can I compare two JSON strings ignoring nulls in Java?
问题
期望:
{ "field1":"value1"}
实际匹配:
{ "field1":"value1", "field2":null}
实际不匹配:
{ "field1":"value1", "field2":"non-null"}
英文:
I want to be able to compare two JSON strings in my tests, but ignoring null fields.
Expected:
{ "field1":"value1"}
Actual and match:
{ "field1":"value1", "field2":null}
Actual and no match:
{ "field1":"value1", "field2":"non-null"}
答案1
得分: 1
我建议去掉空值然后进行比较。
Google GSON在默认情况下在序列化时会忽略空值。
Jackson ObjectMapper 也可以通过一些额外的设置来实现这一点。
在JSON中去掉空值的最直接(不一定是最合适的)方法如下:
Gson gson = new Gson();
String jsonString = "{ \"field1\":\"value1\", \"field2\":null}";
String jsonStringWithoutNulls = gson.toJson(gson.fromJson(jsonString, JsonObject.class));
//结果为 {"field1":"value1"}
英文:
I would recommend to get rid of null values and then compare.
google GSON by default ignores null values while serializing.
Jackson ObjectMapper also can do this with some additional settings.
The most straightforward (not necessarily the most proper) way to get rid of nulls in json would be the following:
Gson gson = new Gson();
String jsonString = "{ \"field1\":\"value1\", \"field2\":null}";
String jsonStringWithoutNulls = gson.toJson(gson.fromJson(jsonString, JsonObject.class));
//results in {"field1":"value1"}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论