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

标签 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();

}}

这就是我分配值并返回列表的方式

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

下面是我的构造函数hotels的样子

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

注意:我重命名是为了尝试遵循更好的命名约定。

关于java - 如何将 JSON 对象添加到 Jax-rs 中的 JSON 响应中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46477468/

相关文章:

java - 构造函数中的多个参数

java - android:在多个 TextView 上绘制连续的字符串

java - 对于接受多个参数的 setter,是否有类似于 @JsonCreator 的注释?

jquery - 通过 jquery ajax 和 javax.ws Web 服务发送 json 作为值失败

java - Google App Engine + Jersey + JSP 结果为 NOT_FOUND

java - JPA 命名存储过程返回简单对象

tomcat - javax.net.ssl.SSLException : Received fatal alert: unexpected_message using jersey 1 client 异常

java - Jersey Web 服务中的 PathParam 值为 null

java - Jersey:当类同时具有 JAX-RS 和 JAX-WS 注释时出错

java - 在 Java 中重定向子进程的 I/O(为什么 ProcessBuilder.inheritIO() 不起作用?)