c# - C#读取JsonResult对象的方法

标签 c# jsonresult

我正在尝试反序列化我的 jsonresult 但我收到以下错误消息:

"Cannot convert from System.Web.Mvc.Result to string"

这是我的 json 结果:

[{"description":"BANANA","quantity":"12","productPrice":"40000","discount":"","isTaxable":true,"finalPrice":"9999","lineItemTotal":"999","orderId":8},{"description":"APPLES","quantity":"20","productPrice":"860000","discount":"","isTaxable":false,"finalPrice":"12000","lineItemTotal":"10000","orderId":8}]

这是我的 Controller 方法:

 [System.Web.Mvc.HttpPost]
        public JsonResult CreateLineItems(JsonResult data)
        {


           ResultDto dto = JsonConvert.DeserializeObject<ResultDto>(data);
            //for (int i = 0; i < data.Data; i++)
            //{
            //    
            //}

            return data;
        }

这是我的 ResultDto 类:

public class ResultDto
    {

        public string description { get; set; }
        public string quantity { get; set; }
        public string productPrice { get; set; }
        public string discount { get; set; }
        public bool isTaxable { get; set; }
        public string finalPrice { get; set; }
        public string lineItemTotal { get; set; }
        public int orderId { get; set; }
    }

JsonResut 包含两个对象(即香蕉和苹果)。所以,我想遍历数据并获得两个 ResultDtos 。我如何实现这一目标?

这一行给我错误:`ResultDto dto = JsonConvert.DeserializeObject(data);

我正在从 View 发送这样的数据:

$.ajax({
                    url: url,
                    data: {
                        data: JSON.stringify(lineitems)
                    },
                    cache: false,
                    type: "POST",
                    success: function (data) {

                    },
                    error: function (reponse) {
                        alert("error : " + reponse);
                    }
                });

在我的 Controller 中获取此数据(对象数组)的最佳方法是什么?一旦我在我的 Controller 中获得这些数据,我想将它保存在数据库中。所以,我不确定 JsonResult 是否是我的方法的正确返回类型。

最佳答案

您已经有一个 JSON。现在解决您的问题的方法是将您的 JSONObject 字符串化,然后将其反序列化为您想要的类型。

string json = JsonConvert.SerializeObject(jsonResult.Data);
ResultDto dto = JsonConvert.DeserializeObject<ResultDto>(json);

关于c# - C#读取JsonResult对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52421913/

相关文章:

c# - SQLite 的 dotConnect 包不适用于 VS2013 中的 64 位 C# 项目?

c# - JSON Post 我的 .NET MVC 2 Controller 需要什么参数

iphone - 复杂Json解析结果格式

json - 如何设置 JsonRequestBehavior.AllowGet 并返回 JsonResult

c# - 不切换 View 返回 JSONResult

c# - 将 Delphi 代码翻译成 C# (Blowfish)

c# - 这是表达式树的正确用法吗?

c# - Linq 组键不是唯一的

c# - JsonResult 在 ASP.NET CORE 2.1 中返回 Json