2012-01-02 25 views
1

我有一個示例類反序列化JSON無法識別數據到地圖JacksonJson

public class Category { 
private String id ; 
    private String name ; 

private String description ; 

private String image ; 

private String thumbnail ; 
private Map<String, String> custom ; 
} 

我從下面的格式服務器的響應,但例如目的讓我們說這是一個文件cat.json

{"id":"mens","name":"Mens","c__showInMenu":true,"c__enableCompare":false} 

    1 ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally 
    2 Category cat= mapper.readValue(new File("cat.json"), Category.class); 

這工作完全正常的域ID,姓名等 如何編寫自定義解串器,使得在開始c_ json的任何字段推入地圖的習慣嗎?

我是傑克遜的新手,正在使用Springs Rest Template並將其配置爲使用 org.springframework.http.converter.json.MappingJacksonHttpMessageConverter

回答

0

這是可能的,但我唯一能想到的方式遠非「乾淨而完美」。 我會建議在使用它之前,通過傑克遜文檔挖掘,作爲最後的措施

你可以做什麼是創建地圖領域的類將舉行序列化對象的所有屬性,就像這樣:

public class CustomObject { 
    private Map<String,Object> map; 
} 

這樣,傑克遜可以解析這樣的對象:

{ map : {"id":"mens","name":"Mens","c__showInMenu":true,"c__enableCompare":false}} 

現在,你仍然有不需要的「地圖」包裝,這會搞亂反序列化。一種解決方案可能是用「{map:」和結束標記「}」來包圍傳入的JSON內容。

這樣傑克遜將正確映射您的對象,您將擁有一張所有屬性的地圖,並且您可以遍歷它,通過instanceof獲取檢查類型並檢索所有數據。

再次,這可能不是最好的辦法,你應該先嚐試更清潔的解決方案。我不是傑克遜的專家,所以我不能指出你有更好的方向。

2

您可能只想簡單地使用@JsonAnySetter

import java.io.File; 
import java.util.HashMap; 
import java.util.Map; 

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

public class JacksonFoo 
{ 
    public static void main(String[] args) throws Exception 
    { 
    ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY); 
    Category category = mapper.readValue(new File("cat.json"), Category.class); 
    System.out.println(category); 
    // output: 
    // Category: id=mens, name=Mens, description=null, image=null, thumbnail=null, custom={c__showInMenu=true, c__enableCompare=false} 
    } 
} 

class Category 
{ 
    private String id; 
    private String name; 
    private String description; 
    private String image; 
    private String thumbnail; 
    private Map<String, String> custom; 

    @JsonAnySetter 
    void addSomething(String name, String value) 
    { 
    if (custom == null) custom = new HashMap(); 
    custom.put(name, value); 
    } 

    @Override 
    public String toString() 
    { 
    return String.format("Category: id=%s, name=%s, description=%s, image=%s, thumbnail=%s, custom=%s", 
     id, name, description, image, thumbnail, custom); 
    } 
} 
+0

該解決方案非常完美。感謝您的反饋 – 2012-01-03 09:04:16