首页 > 解决方案 > 需要解析通过 Post 请求传入的 JSON

问题描述

我正在尝试解析在 Post 请求中收到的 JSON。

JSON如下。它必须不知道有多少记录或字段被称为什么。但是当我通过邮递员发送时,联系人变量始终为空。我把它扔进的班级有问题吗?

{
  "Fields": 
  {
   "first":"fn",
   "last":"ln",
   ...
  }
}
    public class FieldsValues
    {
      List<KeyValuePair<string, string>> Fields =  new List<KeyValuePair<string, string>>() { };
    }

    public void Post([FromBody]FieldsValues Fields)
    {

       ...
    }

我想将 JSON 发送到 Dictionary 对象中,但传入的值始终为 null。

标签: c#json

解决方案


您的 Json 不是数组。您需要方括号来构建数组。除此之外,KeyValuePair 有名为“Key”和“Value”的成员。要匹配,List<KeyValuePair<string, string>>您需要输入如下内容:

{
  "Fields": 
  [{
   "Key":"first",
   "Value":"fn"
  }]
}

如果您自己无法更改 JSON 结构并且您确实不知道该结构,我会选择一种接受原始字符串并使用 Newtonsoft 将该字符串解析为动态对象的方法。例如,此代码可以接受您的 JSON:

        public void Post()
        {
            string text = "";
            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                text = reader.ReadToEnd();

            dynamic dynObj = JObject.Parse(text);

            var firstValue = dynObj.Fields.first.Value;
            ...
        }

推荐阅读