2017-01-08 40 views
0

ObjectMapper是否應該使用只有私有成員,沒有構造函數和沒有getter/setter的類?ObjectMapper限制

我試過了,但並沒有解決問題。

mapper.setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY); 
+0

類*總是*有一個構造函數。你的意思是它只有默認的構造函數嗎? – chrylis

+0

可能重複[如何指定傑克遜只使用字段 - 最好全球](http://stackoverflow.com/questions/7105745/how-to-specify-jackson-to-only-use-fields-preferably- globally) –

+0

@chrylis,這就是我的意思。謝謝寫作 – Andy897

回答

0

http://www.baeldung.com/jackson-field-serializable-deserializable-or-not

static class MyDtoAccessLevel { 
    private String stringValue = "hidden"; 
} 

public static void main(String[] args) throws JsonProcessingException { 
    ObjectMapper mapper = new ObjectMapper(); 
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); 
    MyDtoAccessLevel dtoObject = new MyDtoAccessLevel(); 
    System.out.println(mapper.writeValueAsString(dtoObject)); 
    //prints {"stringValue":"hidden"} 
} 
+0

非常感謝您的寫作。但我使用的是org.codehaus.jackson.map.ObjectMapper,它是com.fasterxml.jackson.core的舊版本。我沒有看到在舊版本中設置PropertyAccessor的選項。 :(想法? – Andy897

+0

而且我沒有線索誰會投下你的答案。 – Andy897

+0

我的代碼樣本是用於Jackson 2.x. Jackson 1.x不再被維護。是否可以切換? –