如何在Java中比较两个JSON字符串,忽略null值?

huangapple go评论64阅读模式
英文:

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"}

huangapple
  • 本文由 发表于 2023年2月14日 00:06:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定