[英]How to add JSON object to my JSON response in 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();
}}
这就是我分配值并返回列表的方式
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"
}]}
您期望的是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;
}}
注意:由我重命名以尝试遵循更好的命名约定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.