Spring MVC - 使用List <custom>属性</custom>返回JSON对象

时间:2013-12-09 07:40:39

标签: java json spring spring-mvc

我的spring mvc控制器上有以下映射:

   @RequestMapping(value = "/servers", method = RequestMethod.GET)

    public @ResponseBody Server getServers(@RequestParam(value="password", required=false) String password)
    {

        Server server = new Server();
        server.setIpaddress("192.168.0.4");
        server.setServername("serverOne");

        List<Service> list = new ArrayList<Service>();   

        Service s1 = new Service();
        s1.setServiceName("telnet");
        s1.setServicePort(21);
        list.add(s1);
        s1= new Service();
        s1.setServiceName("SSH");
        s1.setServicePort(22);
        list.add(s1);

        server.SetServices(list);
        return server;

    }

它应该在json中返回一个服务器类,其中一个fill属性与List匹配 但是没有显示任何东西。这是涉及的课程:

班级服务器:

package es.landesoft.mvctesting.JavaBeans;

import java.util.List;


public class Server {


    private String ipaddress;
    private String serverName;
    private List<Service> services;

    public void setIpaddress(String value)
    {
        this.ipaddress = value;     
    }

    public String getIpAddress()
    {
        return this.ipaddress;  
    }

    public void setServername (String value)
    {       
        this.serverName= value;
    }

    public String getServername()
    {
        return this.serverName;     
    }

    public void SetServices(List<Service> services)
    {
        this.services= services;
    }

    public List<Service> GetServices()
    {
        return this.services;
    }

}

班级服务:

package es.landesoft.mvctesting.JavaBeans;

public class Service
{
    private String serviceName;
    private int servicePort;

    public void setServiceName(String value)
    {
        this.serviceName= value;
    }

    public String getServiceName(){
        return this.serviceName;
    }

    public void setServicePort(int value)
    {
        this.servicePort=value;
    }

    public int getServicePort()
    {
        return this.servicePort;
    }

}

Json输出是:

  

{ “服务器名”: “serverOne”, “ip地址”: “192.168.0.4”}

没有List属性的跟踪。 我做错了什么。

1 个答案:

答案 0 :(得分:2)

喜欢这个

像这样更改您的服务器型号。

public class Server {

   private List<Service> services = new ArrayList<Service>();
}

并添加如下。

Server server = new Server();
server.setIpaddress("192.168.0.4");
server.setServername("serverOne");
Service s1 = new Service();
s1.setServiceName("telnet");
s1.setServicePort(21); 
server.GetServices().add(s1); //Add like this.

注意:维护java命名约定。

 public List<Service> GetServices(){}

应为public List<Service> getServices()

同样适用于二传手。