SerializerProvider
有一個方法稱爲getLocale()
。它返回默認語言環境(請參閱here),但實際上它從SerializationConfig
獲取語言環境信息,您可以使用with
(請參閱here)將其配置爲獲取所需的語言環境。
編輯: 我真的不知道你的MyCustomSeralizer
樣子,但你應該寫這樣的
public class MyCustomSerializer extends SerializerBase<ClassToBeSerialized> {
public MyCustomSerializer() {
super(ClassToBeSerialized.class);
}
@Override
public void serialize(ClassToBeSerialized yourClass,
JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException, JsonGenerationException {
jsonGenerator.writeStartObject();
try {
jsonGenerator.writeFieldName("big (" + yourClass.getLocale().toString() + ")");
jsonGenerator.writeString(getLocaleSpecificSerializedValue(yourClass.getBig(), yourClass.getLocale()));
} catch (ParseException e) {
e.printStackTrace();
}
jsonGenerator.writeEndObject();
}
private String getLocaleSpecificSerializedValue(BigDecimal big, Locale locale) throws ParseException {
NumberFormat nf = NumberFormat.getInstance(locale);
return nf.parse(big.toString()).toString();
}
}
自定義序列它以後註冊的對象映射
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule("BigDecimalModule", new Version(0, 1, 0, "alpha"));
module.addSerializer(ClassToBeSerialized.class, new MyCustomSerializer());
mapper.registerModule(module);
取看看Jackson How-To: Custom Serializers。
我有一個MyClass的列表。我正在使用Spring MVC將列表序列化爲JSON。列表中的MyClass的每個實例都有一個BigDecimal和一個Locale。我想根據區域設置序列化每個BigDecimal(對於每個實例可能不同)。我如何爲每一行定製SerializationConfig? –