How to create generic json response Object in java?

拈花ヽ惹草 提交于 2019-12-08 08:16:53

问题


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.


回答1:


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.




回答2:


You should not maintains status code, message and result within json body.

  1. Response message should only contain the result of that api.
  2. Httpstatus code will be the status code (Ex.200 is success, 404 is notfound)
  3. All the other info should be maintained in response headers, not within json body


来源:https://stackoverflow.com/questions/48485363/how-to-create-generic-json-response-object-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!