2015-05-03 87 views
0

我有一個帶有語言環境和BigDecimal的Java類。我目前正在序列化的BigDecimal與@Seralize註釋:傑克遜json格式貨幣符號

@JsonSerialize(using = MyCustomSeralizer.class) 

我的挑戰是,我想基於類的語言環境將序列值增加一個貨幣符號。有沒有任何方法將語言環境傳遞給序列化程序?或者有關如何最好地格式化數據的建議?數據是用Spring JDBC檢索的。

謝謝。

回答

1

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

+0

我有一個MyClass的列表。我正在使用Spring MVC將列表序列化爲JSON。列表中的MyClass的每個實例都有一個BigDecimal和一個Locale。我想根據區域設置序列化每個BigDecimal(對於每個實例可能不同)。我如何爲每一行定製SerializationConfig? –