2011-12-06 42 views
2

Jackson有一個幫助器方法來返回給定bean字段名稱的@JsonProperty批註值(即JSON屬性鍵)嗎?傑克遜JSON @JsonProperty映射的幫助器方法

語境:

我使用傑克遜客戶端提供的JSON轉換成一個Bean,然後使用JSR-303來驗證豆。當驗證失敗時,我需要向客戶端報告有意義的錯誤消息。驗證對象引用bean屬性;該錯誤消息應引用JSON屬性。因此需要從一個映射到另一個。

回答

3

您可以通過BeanDescription對象中獲取相當多的信息,儘管得到一個相當棘手的(主要是因爲它是專爲傑克遜的內部使用居多)。 但是這是由幾個傑克遜擴展模塊使用的,所以它支持用例。所以:

ObjectMapper mapper = ...; 
JavaType type = mapper.constructType(PojoType.class); // JavaType to allow for generics 
// use SerializationConfig to know setup for serialization, DeserializationConfig for deser 
BeanDescription desc = mapper.getSerializationConfig().introspect(type); 

如果有必要,您也可以安全地將其上傳到BasicBeanDescription

這使您可以訪問大量的信息;邏輯屬性列表(通過它可以找到代表它的getter/setter/field/ctor-argument),完全解析的方法(帶註釋)等等。所以希望這已經足夠了。 邏輯屬性很有用,因爲它們包含外部名稱(JSON中的一個)和從getter/setter派生的內部名稱。

0

我不知道傑克遜有什麼特別容易的東西。基於思考的解決方案可能就足夠了。

import java.lang.reflect.Field; 

import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; 
import org.codehaus.jackson.annotate.JsonMethod; 
import org.codehaus.jackson.annotate.JsonProperty; 
import org.codehaus.jackson.map.ObjectMapper; 

public class JacksonFoo 
{ 
    public static void main(String[] args) throws Exception 
    { 
    // {"$food":"Green Eggs and Ham"} 
    String jsonInput = "{\"$food\":\"Green Eggs and Ham\"}"; 

    ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY); 
    Bar bar = mapper.readValue(jsonInput, Bar.class); 

    new Jsr303().validate(bar); 
    // output: 
    // I do not like $food=Green Eggs and Ham 
    } 
} 

class Bar 
{ 
    @JsonProperty("$food") 
    String food; 
} 

class Jsr303 
{ 
    void validate(Bar bar) throws Exception 
    { 
    Field field = Bar.class.getDeclaredField("food"); 
    JsonProperty annotation = field.getAnnotation(JsonProperty.class); 
    System.out.printf("I do not like %s=%s", annotation.value(), bar.food); 
    } 
}