首页 > 解决方案 > 在 C# 中解析 Json 格式数据时出错

问题描述

我正在研究 .net core api 和 angular 7。我从 angular 项目中调用我的 api,并将 json 格式的数据作为 api 的输入传递。我想解析该 json 格式的数据并从该数据中获取每个值并将其传递给过程。解析数据时出现以下错误:

'Newtonsoft.Json.Linq.JObject.Parse(string)' 的最佳重载方法匹配有一些无效参数

这是我的 json 格式数据:

{
    "bu":2,
    "level":60,
    "location":124160,
    "month":"FEB",
    "year":2018,
    "PROCNAME":"proc_plan_wise_adhoc_rpt_n#200",
    "CLIENTID":"CIPQ",
    "REPCODE":"A0200"
}

我想将 bu、level、location 等的值获取到变量中并将其传递给程序,如何获取这些值?

这是我的api代码:

[HttpPost]
[Route("bindgenericreports")]
public IActionResult BindGenericReports([FromBody]dynamic data)
{
    try
    {
        rs = new ResponseModel();
        ReportDL objReportDL = new ReportDL(_configuration);
        var details = JObject.Parse(data); //i'm getting error in this line

        string bu = details["bu"].ToString();

        //rs = objReportDL.BindGenericReports(data);
        return Ok(rs);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        rs = null;
    }
}

可能是什么问题?请帮忙。

更新

邮差

.net 核心

标签: c#json

解决方案


错误消息中已经提供了答案。

'Newtonsoft.Json.Linq.JObject.Parse(string)' 的最佳重载方法匹配有一些无效参数

您正在尝试解析显然不是字符串的动态。尝试将动态转换为字符串值。如果它是一个字符串值,您将能够解析它。

var details = JObject.Parse(data.ToString());

从 OP 更新

您使用 Postman 发送的 Json 不正确。尝试使用JsonLint解析 json 以创建有效的 Json


推荐阅读