JsonConverter Serialize失败 - 返回一个字符串而不是json对象

时间:2018-03-16 22:10:50

标签: .net json asp.net-web-api serialization

我不确定发生了什么,但突然之间,我的控制器出现了奇怪的行为。

控制器设置为返回一个json序列化对象,如下所示:

return Ok(JsonConvert.SerializeObject(result, Formatting.Indented));

它工作正常,但现在又回来了:

"{\r\n  \"ProductID\": 1,\r\n  \"ArticleID\": \"a1\",\r\n  \"ProductDescription\": \"new dress\",\r\n  \"ProductType\": \"1\",\r\n  \"MaterialDescription\": \"cotton\",\r\n  \"Qty\": 1,\r\n  \"SizeID\": 1,\r\n  \"RetailPrice\": 22.00,\r\n  \"ImagePath\": \"C:\\\\Users\\\\Harry\\\\Desktop\\\\IMG_8931.JPG\",\r\n  \"ProductVaritiesID\": 1,\r\n  \"Discount\": 0.00,\r\n  \"QuantityInStock\": 10,\r\n  \"ProductTypeID\": 1,\r\n  \"ProductOrderQuantity\": 0\r\n}"

但是,如果我返回此对象而不进行如下序列化:

        return Ok(result);

它返回一个像这样的对象:

{
    "ProductID": 1,
    "ArticleID": "a1",
    "ProductDescription": "new dress",
    "ProductType": "1",
    "MaterialDescription": "cotton",
    "Qty": 1,
    "SizeID": 1,
    "RetailPrice": 22,
    "ImagePath": "C:\\Users\\Harry\\Desktop\\IMG_8931.JPG",
    "ProductVaritiesID": 1,
    "Discount": 0,
    "QuantityInStock": 10,
    "ProductTypeID": 1,
    "ProductOrderQuantity": 0
}

Controller:
        [EnableCors(origins: "*", headers: "*", methods: "GET")]
        [Route("api/product/getproductbybarcode")]
        [ResponseType(typeof(Product))]
        public IHttpActionResult GetProductByBarcode(string barcodevalue)
        {
            if (string.IsNullOrEmpty(barcodevalue))
                return NotFound(); //replace with correct message

            var result = _iproduct.GetProductByBarcode(barcodevalue);

            return Ok(JsonConvert.SerializeObject(result, Formatting.Indented));
        }

我无法弄清楚是什么导致Json序列化失败?

3 个答案:

答案 0 :(得分:0)

也许您将方法从MVC移动到MVC Web Api,因为默认情况下Api序列化对象,这就是想法,您不必像在MVC应用程序中那样调用序列化程序(不是Api)< / p>

所以这个

[HttpGet]
        [Route("Api/Values/GetByID")]
        [ActionName("GetByID")]
        public dynamic GetByID(int id)
        {
            return new {name = "Joe", value = "team" };
        }

Retutns

{
    "name": "Joe",
    "value": "team"
}

这个

[HttpGet]
        [Route("Api/Values/GetByID")]
        [ActionName("GetByID")]
        public dynamic GetByID(int id)
        {
            return JsonConvert.SerializeObject(new { name = "Joe", value = "team" }, Formatting.Indented);
        }

返回

"{\r\n  \"name\": \"Joe\",\r\n  \"value\": \"team\"\r\n}"

这是因为它以某种方式序列化了两次

答案 1 :(得分:0)

尝试以下代码

string jsonFormatted = JValue.Parse(json).ToString(Formatting.Indented);

查看以下链接了解更多详情 https://weblog.west-wind.com/posts/2015/Mar/31/Prettifying-a-JSON-String-in-NET

同时确保content-type:application/json

答案 2 :(得分:0)

JsonConvert.SerializeObject为您提供了一个字符串作为返回类型。如果您在序列化后返回响应,那么您将获得字符串响应,如果您返回对象,那么您将获得json对象作为响应。