B.Vyas
B.Vyas

Reputation: 43

How to Format List in HttpResponseMessage in WEB API

Here, I want the list "User" as a response. But it contains Message also. I want the message to be printed only once. Currently it is printing user.count times.

for (int i = 0; i < user.Count; i++)
 {
   if (user[i].Message == "Success")
      {
        resp = new HttpResponseMessage { Content = new ObjectContent(typeof(List<GetUserList>), user, GlobalConfiguration.Configuration.Formatters.JsonFormatter) };
       }
   else
      {
        resp = new HttpResponseMessage { Content = new StringContent("[{\"Message\":\"" + user[i].Message + "\"}]", System.Text.Encoding.UTF8, "application/json") };
       }
 }

The result should be like this:

{
  "message": " Successful",
  "supervisorlist": [
  {
    " userID ": "654",
    " forename ": "John"
  },
  {
    " userID ": "655",
    " forename ": "Jack"
  }
 ]

}

Upvotes: 1

Views: 7503

Answers (2)

Nkosi
Nkosi

Reputation: 247018

bool includeMessage = users.Any(u => u.Message == "Success");
object content = null;

if(includeMessage) {
    content = new { message = "Success", supervisorlist = users };
} else {
    content = new { supervisorlist = users };
}

resp = new HttpResponseMessage { 
            Content = new StringContent(JsonConvert.SerializeObject(content), System.Text.Encoding.UTF8, "application/json") 
        };

Upvotes: 0

Alex S
Alex S

Reputation: 111

example for Success

var responseObj = new { message = "Successful", supervisorlist = users };

resp = new HttpResponseMessage 
        { 
            Content = new StringContent(JsonConvert.SerializeObject(responseObj), 
                                            System.Text.Encoding.UTF8, "application/json") 
        };

Upvotes: 4

Related Questions