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

时间:2017-09-28 20:07:59

标签: java jersey jax-rs

我的主资源文件

public class MyResource {


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

}}

这就是我分配值并返回List

的方法
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 个答案:

答案 0 :(得分:1)

您期待的是List<Hotels>的包装,您可以为其定义一个模型,说明您现有的模型 - HotelServices as -

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;
}}

注意 :由我重命名以尝试遵循更好的命名约定。