Quantcast
Channel: Question and Answer » json
Viewing all articles
Browse latest Browse all 148

Best way to represent multiple JSON response in a REST service? [closed]

$
0
0

I am working on a REST service in which I am trying to come up with a JSON response that I am supposed to return back. Below is the design I am able to come up with in which each line is a response for each request so we have total three response for three request wrapped around an array.

In this I will pass HTTP Status code as 200:

[
    { "response": "{"hello":1,"world":"4"}", "aging": "123456", "bandwidth": "100" , "error": "OK", "status": "SUCCESS" }
    { "response": "{"hello":2,"world":"5"}", "aging": "5432", "bandwidth": "134" , "error": "OK", "status": "SUCCESS" }
    { "response": "{"hello":3,"world":"6"}", "aging": "6789", "bandwidth": "234" , "error": "OK", "status": "SUCCESS" }
]

In the same way, I can have below response as well if any request failed and send HTTP Status code as 202 since it’s a partial response.

[
    { "response": "{"hello":1,"world":"4"}", "aging": "123456", "bandwidth": "100" , "error": "OK", "status": "SUCCESS" }
    { "response": null, "aging": "0", "bandwidth": "0" , "error": "Some Error", "status": "ERROR" }
    { "response": "{"hello":3,"world":"6"}", "aging": "6789", "bandwidth": "234" , "error": "OK", "status": "SUCCESS" }
]

In the same way, I can have below response if all request failed.

[
    { "response": null, "aging": "0", "bandwidth": "0" , "error": "Some Other Error", "status": "ERROR" }
    { "response": null, "aging": "0", "bandwidth": "0" , "error": "Some Error", "status": "ERROR" }
    { "response": null, "aging": "0", "bandwidth": "0" , "error": "Some New Error", "status": "ERROR" }
]

I am getting above JSON response by serializing below response object:

public class TestResponse {

    private final String response;
    private final ErrorCodeEnum error;
    private final StatusCodeEnum status;
    private final String aging;
    private final String bandwidth;

    // .. constructors and getters here
}

I am trying to understand, is this the best design for returning JSON response for multiple response cases in a REST service? Or is there any better way to return a JSON response with all the proper fields?

The only problem I have is – for successful response, my JSON string is escaped with slashes in response filed in my final JSON. Not sure whether that’s a good approach in REST service.

My rest service will call a library which it is using internally and that library will return back a List and then I am serializing this List into JSON Array as shown above.


Viewing all articles
Browse latest Browse all 148

Trending Articles