2016-07-04 59 views
1

如何獲取包含java對象的json,但使用鍵作爲數組的標識符? 我在Spring mvc 4.x中有以下內容。我使用傑克遜庫來將對象編組爲json。Spring Web MVC JSON - 傑克遜鍵/對象數組的名稱(命名數組)

@RequestMapping(value="dogs") 
    public List<Dog> getDogs(){ 
     List<Dog> list_dogs = new ArrayList<Dog>(); 
     list_dogs.add(new Dog("dog1",1)); 
     list_dogs.add(new Dog("dog2",2)); 
     return list_dogs; 
    } 

我得到如下回應:[{"name":"dog1","age":1},{"name":"dog2","age":2}]

我想有它類似如下:

{ 
    "array": [{ 
     "name": "dog1", 
     "age": 1 
    }, { 
     "name": "dog2", 
     "age": 2 
    }] 
} 

如何提供對數組的名字嗎?

回答

1

好的,使用一個地圖,而不是一個列表。

@RequestMapping(value="dogs") 
public Map<String, List<Dog>> getDogs(){ 
    Map<String, List<Dog>> map = new HashMap<String, List<Dog>>(); 
    List<Dog> list_dogs = new ArrayList<Dog>(); 
    list_dogs.add(new Dog("dog1",1)); 
    list_dogs.add(new Dog("dog2",2)); 
    map.put("myArray", list_dogs); 
    //return list_dogs; [{"name":"dog1","age":1},{"name":"dog2","age":2}] 
    return map;  //{"myArray":[{"name":"dog1","age":1},{"name":"dog2","age":2}]} 
} 

{"myArray":[{"name":"dog1","age":1},{"name":"dog2","age":2}]} 
0

您期待的響應是json對象而不是json數組。 因此,使用所需的密鑰創建json對象/地圖

@RequestMapping(value="dogs") 
public Map<String, List<Dog>> getDogs(){ 
    List<Dog> list_dogs = new ArrayList<Dog>(); 
    list_dogs.add(new Dog("dog1",1)); 
    list_dogs.add(new Dog("dog2",2)); 
    Map<String, List<Dog>> map = new HashMap<>(); 
    map.put("array", list_dogs); 
    return map; 
}