2011-07-01 40 views
11

我想安裝Jackson JSON自定義解串器將JSON值轉換爲長對象。 我按照本網站上的說明:http://wiki.fasterxml.com/JacksonHowToCustomDeserializers來設置自定義解串器。設置JSON自定義解串器

但是,對於定製解串器來說,我必須總是每次註釋 例如

public class TestBean { 
    Long value; 

    @JsonDeserialize(using=LongJsonDeserializer.class) 
    public void setValue(Long value) { 
     this.value = value; 
    } 
} 

有沒有辦法每次都告訴傑克遜總是使用自定義解串器龍反序列化,而不必使用@JsonDeserialize(使用= LongJsonDeserializer.class)註釋?

回答

27
LongJsonDeserializer deserializer = new LongJsonDeserializer(); 

SimpleModule module = 
    new SimpleModule("LongDeserializerModule", 
     new Version(1, 0, 0, null)); 
module.addDeserializer(Long.class, deserializer); 

ObjectMapper mapper = new ObjectMapper(); 
mapper.registerModule(module); 

這裏有一個完整的演示應用程序。這適用於傑克遜的最新版本,也可能與傑克遜的版本回到1.7。

import java.io.IOException; 

import org.codehaus.jackson.JsonParser; 
import org.codehaus.jackson.JsonProcessingException; 
import org.codehaus.jackson.Version; 
import org.codehaus.jackson.map.DeserializationContext; 
import org.codehaus.jackson.map.JsonDeserializer; 
import org.codehaus.jackson.map.ObjectMapper; 
import org.codehaus.jackson.map.module.SimpleModule; 

public class Foo 
{ 
    public static void main(String[] args) throws Exception 
    { 
    TestBean bean = new TestBean(); 
    bean.value = 42L; 

    ObjectMapper mapper = new ObjectMapper(); 

    String beanJson = mapper.writeValueAsString(bean); 
    System.out.println(beanJson); 
    // output: {"value":42} 

    TestBean beanCopy1 = mapper.readValue(beanJson, TestBean.class); 
    System.out.println(beanCopy1.value); 
    // output: 42 

    SimpleModule module = 
     new SimpleModule("LongDeserializerModule", 
      new Version(1, 0, 0, null)); 
    module.addDeserializer(Long.class, new LongJsonDeserializer()); 

    mapper = new ObjectMapper(); 
    mapper.registerModule(module); 

    TestBean beanCopy2 = mapper.readValue(beanJson, TestBean.class); 
    System.out.println(beanCopy2.value); 
    // output: 126 
    } 
} 

class TestBean 
{ 
    Long value; 
    public Long getValue() {return value;} 
    public void setValue(Long value) {this.value = value;} 
} 

class LongJsonDeserializer extends JsonDeserializer<Long> 
{ 
    @Override 
    public Long deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException 
    { 
    Long value = jp.getLongValue(); 
    return value * 3; 
    } 
} 
+1

這與http://wiki.fasterxml.com/JacksonHowToCustomDeserializers中描述的相同,我已經遵循了! – missionE46

+0

啊。也許,我太快讀了原始問題。再看看... –

+0

我最初發布的內容解決了您正確詢問的問題。我將用完整的演示應用程序更新這篇文章。 –