我正在尝试实现自定义JSON序列化程序类,以将对象BigInteger
的值显示为JSON响应中的字符串。
我实现了一个自定义的序列化器类
public class CustomCounterSerializer extends StdSerializer<BigInteger> {
private static final long serialVersionUID = 5440920327083673598L;
public CustomCounterSerializer() {
this(BigInteger.class);
}
public CustomCounterSerializer(Class<BigInteger> vc) {
super(vc);
}
@Override
public void serialize(BigInteger value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
BigInteger valueJson = value==null ? BigInteger.valueOf(0) : value;
jsonGenerator.writeString(valueJson.toString());
}
}
我遇到的问题是我想使用重写的方法处理null
对象的值,并将0
传递给JSON字符串而不是null
。
我为此编写了一个JUnit测试:
public class CustomCounterSerializerTest {
private ObjectMapper objectMapper = new ObjectMapper();
@After
public void tearDown() {
objectMapper = null;
}
@Test
public void testCustomSerializerWithNullValues() throws JsonParseException, JsonMappingException, IOException {
MyObject obj = new MyObject();
obj.setNonNullValue(BigInteger.valueOf(1);
String obj_ = objectMapper.writeValueAsString(obj);
assertThat(obj_).isNotNull();
assertTrue(obj_.contains("\"nonNullValue\":\"" + BigInteger.valueOf(1).toString() + "\",\"nullValue\":\""+ BigInteger.valueOf(0).toString() +"\""));
}
}
它失败,因为它包含null
而不是nullValue:"0"
。
但是对象的null
值始终不传递给args构造函数,甚至像this(BigInteger.class)
不使用我的方法并显示null
一样。
答案 0 :(得分:1)
您需要告诉Jackson,它应该使用序列化程序
即使是空值。您可以使用override fun getChildView(
groupPosition: Int, childPosition: Int,
isLastChild: Boolean, convertView: View?, parent: ViewGroup
): View {
var convertView = convertView
val childText = getChild(groupPosition, childPosition) as String
if (convertView == null) {
val infalInflater = this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
convertView = infalInflater.inflate(R.layout.list_item, null)
}
val txtListChild = convertView!!.findViewById(R.id.lblListItem) as TextView
val switch = convertView.findViewById<Switch>(R.id.switchView)
val count = getChildrenCount(groupPosition)
switch.setOnCheckedChangeListener{ compoundButton: CompoundButton, b: Boolean ->
}
txtListChild.text = childText
return convertView
}
以及nullsUsing
参数。
在MyObject类中,它看起来像这样:
@JsonSerializer