我有一个类 MySimpleObject,它有各种成员字段。给定一个 json,它将相应地填充该字段。但是,如果 json 被声明为“nil”,我计划将其设置为 null 而不是字符串“nil”。
下面的示例应该结果是一个 MySimpleObject,其所有字段都为 null,以及 subItemList
的 0 长度列表。 myObj1
应等于 myObj2
。
@Test
public void myTestFunction() {
String myJson1 = "{\"item1\":\"nil\",\"item2\":\"nil\",\"subItemList\":[{\"subItem1\":\"nil\",\"subItem2\":\"nil\"}]}";
String myJson2 = "{\"subItemList\":[]}";
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(new TypeToken<List<MySubItems>>(){ }.getType(), new MyOwnListDeserializer());
gsonBuilder.registerTypeAdapter(String.class, new MyOwnStringDeserializer());
Gson gson = gsonBuilder.create();
MySimpleObject myObj1 = gson.fromJson(myJson1, MySimpleObject.class);
MySimpleObject myObj2 = gson.fromJson(myJson2, MySimpleObject.class);
assertThat(myObj1.equals((myObj2))).isTrue();
}
class MySimpleObject implements Serializable {
String item1 = null;
String item2 = null;
List<MySubItems> subItemList;
@Override
public int hashCode() {
int hash = 17;
hash = 31*hash + ((item1 == null)? 0 :item1.hashCode());
hash = 31*hash + ((item2 == null)? 0 :item2.hashCode());
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof MySimpleObject) {
return this.hashCode() == obj.hashCode();
}
return super.equals(obj);
}
}
class MySubItems implements Serializable {
String subItem1 = null;
String subItem2 = null;
@Override
public int hashCode() {
int hash = 17;
hash = 31*hash + ((subItem1 == null)? 0 :subItem1.hashCode());
hash = 31*hash + ((subItem2 == null)? 0 :subItem2.hashCode());
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof MySubItems) {
return this.hashCode() == obj.hashCode();
}
return super.equals(obj);
}
}
如何编写自定义序列化程序,而不必循环遍历每个 jsonObject 并检查“nil”是否设置为 null?
最佳答案
我查看了 Gson 库以及 gson-fire project ,但它们似乎都不允许提供真正的通用(和高性能)解决方案。
一种方法是在将 json 字符串传递给 gson 对象之前系统地用 "null"
替换 "nil"
。它不是很干净,但性能相当好并且可以工作。
这是一个基本方法(必须改进):
public static String convertNil( String json ){
return json.replaceAll( ":\\s*\"nil\"", ": null" );
}
然后像这样使用它:
MySimpleObject myObj1 = gson.fromJson( convertNil( myJson1 ), MySimpleObject.class );
MySimpleObject myObj2 = gson.fromJson( convertNil( myJson2 ), MySimpleObject.class );
关于java - 如何为类的所有字段编写通用的自定义GSON反序列化器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39661361/