代码之家  ›  专栏  ›  技术社区  ›  Deepak Prabhu

如何在Jax rs中将JSON对象添加到我的JSON响应中?

  •  1
  • Deepak Prabhu  · 技术社区  · 7 年前

    public class MyResource {
    
    
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/getAll")
    public List<hotels> getResources() throws IOException {
        hotelServices services = new hotelServices();
        return services.getAllHotels();
    
    }}
    

    这就是我赋值和返回列表的方式

    public class hotelServices {
    
    public List<hotels> getAllHotels() throws IOException
    
    {
        List<hotels> list = new ArrayList<hotels>();    
    
    
            String ID =  "73";
            String HoteName = "KKR"
            String Location = "Kelambakkam"
            String Ratings = "2"
            String Landmark = "Opp to R&G"
            hotels thisHotel = new hotels(ID,HotelName,Location,Ratings,Landmark);
            list.add(thisHotel);
            return list;
    }   }   
    

    下面是我的构造函数 看起来像

    public hotels(String id, String hotelName,String location, String ratings, String landmark)
    {
    
        this.id = id;
        this.hotelName = hotelName;
        this.location=location;
        this.ratings = ratings;
        this.landmark = landmark;
    }
    

    我收到这样的回复

    [{  
      "hotelName":" KKR",
      "id":" 73",
      "landmark":" Opp to R&G",
      "location":" Kelambakkam",
      "ratings":" 2"
    }]
    

    我试图用Json对象生成这样的东西,但我做不到。有什么可以帮我的吗??

    {"hotels":[{  
      "hotelName":" KKR",
      "id":" 73",
      "landmark":" Opp to R&G",
      "location":" Kelambakkam",
      "ratings":" 2"
     }]}
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Naman    7 年前

    List<Hotels> 你可以定义一个模型,比如说你已经存在的模型- HotelServices

    class HotelServices {
        List<Hotels> hotels; // do all the logic of setting this value as you currently do
     }
    

    并将您的资源修改为:

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/getAll")
    public HotelServices getResources() throws IOException {
        HotelServices services = new HotelServices(); // assuming you would assign value to this 
        return services;
    }}
    

    笔记