如何在java中创建通用的json响应对象? [英] How to create generic json response Object in java?

查看:85
本文介绍了如何在java中创建通用的json响应对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我创建了许多GET,POST Web服务,它们具有不同的不同类型的基本上是模型对象的响应,并且取决于媒体类型,我得到JSON或XML。

有些响应是只有一个对象在{}中以JSON显示,有些则是在[]中的列表。
我希望看到所有api响应的通用响应格式。


$ b

示例 -
{status:0或1,message:任何字符串消息,结果:它可以是单个对象,也可以是根据每个Web服务响应动态变化的对象列表。}

因为在这里我们需要创建用于获取响应的模型对象,所以我创建了一个ResponseModel,它具有状态属性,消息属性但不知道结果属性的类型,因为有时候它可以有单个对象或某个列表,所以我应该为此设置哪种类型属性,以便我可以为此分配任何东西,响应将始终采用JSON或XML相同的格式。



我创建了一个带构造函数的静态方法,它将所有这些三个参数并创建一个ResponseModel对象。



在此先感谢
$ b EDITED-使用Object泛型

  public static Response getResponseObjectIsValid(boolean isValid,String messa ge,Object result)
{


if(isValid == true){
LGSResponse response = new LGSResponse();
response.setStatus(1);
response.setMessage(message.length()> 0?message:Success);
response.setResult(result);

返回Response.status(Status.OK).entity(response).build();

}
else
{
LGSResponse response = new LGSResponse();
response.setStatus(1);
response.setMessage(message.length()> 0?message:Failed);
response.setResult(result);

返回Response.status(Status.OK).entity(response).build();


结果参数是普通模型对象。

解决方案

您可以简单地按照您的说法创建您的课程。

  public class ResponseModel {
int status;
字符串消息;
对象结果;

//构造函数,getters,setters去这里......
//(可能考虑使用lombok,但这是另一个故事)
}

然后,您可以传递单个对象或数组作为第三参数,而json / xml序列化器应该处理除非你的对象非常复杂(我很少遇到这个问题)。

b
$ b

  //在响应模型中返回单个对象
@GET
@Path(/ myMethod)
public response aJerseyMethod(){

Book aBookObject = new Book(The Title,Name of Author);

ResponseModel responseModel = new ResponseModel(1,This is a book,aBookObject);

return Response.ok(responseModel)
.build();


//在响应模型中返回数组
@GET
@Path(/ myOtherMethod)
public Response anotherJerseyMethod(){

预订aBookObject =新书(标题,作者姓名);
Book anotherBookObject = new Book(The Other Title,Name of another Author);

ArrayList< Book> aBookArray = new Arraylist();
aBookArray.add(aBookObject);
aBookArray.add(anotherBookObject);

ResponseModel responseModel = new ResponseModel(1,These are books,aBookArray);

return Response.ok(responseModel)
.build();
}

在这两种情况下,您都应该得到预期的输出结果,不必自己做任何额外的检查或转换。

我只是在这里写了这个,所以试试你自己的类而不是书(这不是一个真正的类),让我知道它是否工作。

I am new to java and creating some Restful services in netbeans using jersey framework.

I have created many GET, POST web services which is having different different type of responses which are basically Model Objects and depending upon media type I am getting JSON or XML.

Some response is having only a single object which is being shown in JSON inside {}, and some are list which are in []. I want to see a generic response format for all api responses.

Example- {"status":"0 or 1", "message":"any string message","result":"it can be a single object or a list of objects which is dynamic depending upon each web service response"}.

Since here in java we need to created model objects for getting responses so I have created a ResponseModel which is having a status property , message property but don't know the type of result property because sometime it can have a single object or sometime a list so what type should I set for this property so that I can assign any thing to this and response will always be in same format for JSON or XML.

I have created a static method with constructor which takes all these three parameters and create a ResponseModel object.

Thanks in advance

EDITED- Code after Using "Object" as generic type

public static Response getResponseObjectIsValid(boolean isValid, String message,Object result)
{


    if (isValid == true) { 
       LGSResponse response = new LGSResponse();
       response.setStatus(1);
       response.setMessage(message.length()>0 ? message : "Success");
       response.setResult(result);

      return  Response.status(Status.OK).entity(response).build();

    }
    else 
    {
      LGSResponse response = new LGSResponse();
      response.setStatus(1);
       response.setMessage(message.length()>0 ? message : "Failed");
       response.setResult(result);

       return  Response.status(Status.OK).entity(response).build();
    }
}

Result Parameter is a normal model object.

解决方案

You can simply create your class as you've said.

public class ResponseModel {
    int status;
    String message;
    Object result;

    // contructor, getters, setters go here...
    // (probably consider using lombok, but that is a story for another time)
}

Then you can pass either a single object or an array as the 3rd param and the json/xml serializer should take care of the conversion for you unless your objects are very complex(I rarely run into that problem)

For example, your Jersey methods would look something like this:

// returning a single object within the response model
@GET
@Path("/myMethod")
public Response aJerseyMethod() {

    Book aBookObject = new Book("The Title", "Name of Author");

    ResponseModel responseModel = new ResponseModel(1, "This is a book", aBookObject);

    return Response.ok(responseModel)
                .build();
}

// returning an array within the response model
@GET
@Path("/myOtherMethod")
public Response anotherJerseyMethod() {

    Book aBookObject = new Book("The Title", "Name of Author");
    Book anotherBookObject = new Book("The Other Title", "Name of another Author");

    ArrayList<Book> aBookArray = new Arraylist();
    aBookArray.add(aBookObject);
    aBookArray.add(anotherBookObject);

    ResponseModel responseModel = new ResponseModel(1, "These are books", aBookArray);

    return Response.ok(responseModel)
                .build();
}

In both cases you should get the expected output you were talking about and you do not have to do any additional checks or conversions yourself.

I just wrote this here, so try it out with your own classes instead of "Book" (which is not a real class) and let me know if it works.

这篇关于如何在java中创建通用的json响应对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆