-
Notifications
You must be signed in to change notification settings - Fork 478
register_custom_reader_writer_cn
温绍锦 edited this page Oct 5, 2022
·
3 revisions
package com.alibaba.fastjson2.writer;
public interface ObjectWriter<T> {
void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features);
}
class InetAddressWriter implements ObjectWriter {
InetAddressWriter INSTANCE = new InetAddressWriter();
@Override
public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) {
if (object == null) {
jsonWriter.writeNull();
return;
}
InetAddress address = (InetAddress) object;
// 优先使用name
jsonWriter.writeString(address.getHostName());
}
}
JSON.register(InetAddress.class, InetAddressWriter.INSTANCE);
JSON.register(Inet4Address.class, InetAddressWriter.INSTANCE);
JSON.register(Inet6Address.class, InetAddressWriter.INSTANCE);
ObjectWriters提供了构造ofToString/ofToInt/ofToLong方法,让使用者能更方便序列化,比如:
public static class Bean {
public int id;
public String toString() {
return Integer.toString(id);
}
public int getId() {
return id;
}
}
@Test
public void testToString() {
ObjectWriter objectWriter = ObjectWriters.ofToString(Bean::toString);
Bean bean = new Bean();
bean.id = 101;
JSONWriter jsonWriter = JSONWriter.of();
objectWriter.write(jsonWriter, bean);
assertEquals("\"101\"", jsonWriter.toString());
}
@Test
public void testToInt() {
ObjectWriter<Bean> objectWriter = ObjectWriters.ofToInt(
(ToIntFunction<Bean>) Bean::getId
);
Bean bean = new Bean();
bean.id = 101;
JSONWriter jsonWriter = JSONWriter.of();
objectWriter.write(jsonWriter, bean);
assertEquals("101", jsonWriter.toString());
}
package com.alibaba.fastjson2.reader;
public interface ObjectReader<T> {
T readObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features);
}
ObjectReader还有很多其他方法,但都提供了缺省实现,上面这个方法是必须实现的。
import java.time.Instant;
import com.alibaba.fastjson2.reader.ObjectReader;
class InstantReader implements ObjectReader {
public static final InstantReader INSTANCE = new InstantReader();
@Override
public Object readObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features) {
if (jsonReader.nextIfNull()) {
return null;
}
long millis = jsonReader.readInt64Value();
return Instant.ofEpochMilli(millis);
}
}
JSON.register(Instant.class, ObjectReader.INSTANCE);
ObjectReaders提供了构造ofString/ofInt/ofLong方法,让使用者能更方便反序列化,比如:
public static class Bean {
final int code;
public Bean(String str) {
code = Integer.parseInt(str);
}
}
@Test
public void test() {
JSON.register(Bean.class, ObjectReaders.ofString(Bean::new));
Bean bean = JSON.parseObject("\"123\"", Bean.class);
assertEquals(123, bean.code);
}