简体   繁体   中英

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"
  }
 ]

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM