简体   繁体   中英

Returning JSON in ASP.NET controller method

I have the following working controller method, which returns the JSON in a simple text format.

[HttpPost]
public IActionResult DecodeBarcode(string productCodeScheme, string productCode, string serialNumber, string batch, string expirationDate, int commandStatusCode) {
    string TextAreaResult = string.Empty;
    try {
        TextAreaResult = string.Format("{0} {1} {2}", request.getHttpInformation(), request.getHttpWarning(), request.getHttpResponseCode());
    } catch (Exception exc) {
        TextAreaResult = "Exception: " + exc.Message;
    }
    return Json(TextAreaResult);
}

The output after the above method is run looks something like

"The pack is active No warning 200"

whereas

request.getHttpInformation() is The pack is active
request.getHttpWarning() is No warning
request.getHttpResponseCode() is 200

Now, I am trying to split the response into 3 different key-value pairs so that my response will look like

{
  httpInformation: "The pack is active",
  httpWarning: "No Warning",
  httpResponseCode: "200"
}

How do I pass the additional params in return Json(TextAreaResult) call?

If I do like the following it won't work

[HttpPost]
public IActionResult DecodeBarcode(string productCodeScheme, string productCode, string serialNumber, string batch, string expirationDate, int commandStatusCode) {
    string TextAreaResult = string.Empty;
    string TextAreaResultHttpInformation = string.Empty;
    string TextAreaResultHttpWarning = string.Empty;
    string TextAreaResultHttpResponseCode = string.Empty;

    try {
        TextAreaResultHttpInformation = string.Format("{0}}", request.getHttpInformation());

        TextAreaResultHttpWarning = string.Format("{1}}", request.getHttpWarning());

        TextAreaResultHttpResponseCode = string.Format("{2}}", request.getHttpResponseCode());
    } catch (Exception exc) {
        TextAreaResult = "Exception: " + exc.Message;
    }

    return Json(TextAreaResultHttpInformation, TextAreaResultHttpInformation, TextAreaResultHttpResponseCode);
}

How do I construct the key-value pairs and return as JSON? Perhaps, Json method is not the right choice over here, but being new to C#, I am not aware of any other c# inbuilt methods for constructing JSON

Assuming you actually want to consume the response as JSON, you could achieve this by doing

return Json(new 
{
    HttpInformation = TextAreaResultHttpInformation, 
    HttpWarning = TextAreaResultHttpWarning,
    StatusCode = TextAreaResultHttpResponseCode
});

You can make wrapper class for these properties and return it.

public class BarcodeResultDto
    {
        [JsonProperty("httpInformation")]
        public string HttpInformation { get; set; }

        [JsonProperty("httpWarning")]
        public string HttpWarning { get; set; }

        [JsonProperty("httpResponseCode")]
        public int GetHttpResponseCode { get; set; }
    }

public IActionResult DecodeBarcode(string productCodeScheme, string productCode, string serialNumber,
            string batch, string expirationDate, int commandStatusCode)
        {
            var barcodeResult = new BarcodeResultDto
            {
                GetHttpResponseCode = 200,
                HttpInformation = "The pack is active",
                HttpWarning = "No Warning"
            };

            // your code here
            return Ok(barcodeResult);
        }

Or you can change retuned value from IActionResult to JsonResult

If you want a different approach then you can use JsonSerializer in the following way :

// Creating BlogSites object  
BlogSites bsObj = new BlogSites()  
{  
   Name = "test-name",  
   Description = "test-description"  
};  

// Serializing object to json data  
JavaScriptSerializer js = new JavaScriptSerializer();  
string jsonData = js.Serialize(bsObj); // {"Name":"test-name","Description":"test-description"}  

You will just need to create a class and store value in its objects then serialize it. If you have a list then you can use List of that class and then serialize.

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