Spring Web MVC Json - jackson键/对象数组的名称(命名数组)

时间:2016-07-04 14:17:26

标签: json spring-mvc jackson

如何获取包含java对象的json,但是使用键作为数组的标识符? 我在Spring mvc 4.x中有以下内容。我使用杰克逊库将对象编组到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
    }]
}

如何提供阵列的名称?

2 个答案:

答案 0 :(得分:1)

好的,使用Map而不是List。

@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}]}

答案 1 :(得分: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;   
}