我有一个MySimpleObject类,它具有各种成员字段。给定一个json,它将相应地填充该字段。但是,如果将json声明为“ nil”,我计划将其设置为null而不是字符串“ nil”。
下面的示例应该是一个MySimpleObject,其所有字段都为null,并且长度为0的subItemList
。 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字符串中的"nil"
用"null"
替换为gcc对象之前,将其替换为。它不是很干净,但是性能很好并且可以工作。
这是一种基本方法(必须完善):
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 );