c# - 需要解析通过 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。
解决方案
您的 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;
...
}
推荐阅读
- node.js - NestJS 返回 HTTP 请求的结果
- java - Java中的空格和换行符是否被视为一个字节?
- scala - 使用 scala 获取数据框中每个类别的列的最大分钟数
- matlab - Matlab动态绘图轴
- ospf - 我应该在核心交换机还是边缘交换机上启用 OSPF?
- asp.net - 在 HTML 表格标签中使用 AngularJS ng-repeat-start 和 ng-repeat-end 的同一实体的嵌套循环
- asp.net - Akka.net 异步方法处理
- mysql - MySQL 语句在更新中使用 group_concat
- python - 我在 Django 应用程序中同一类的两个对象之间存在 OneToOne 关系。是否可以强制执行这种关系的唯一性?
- c# - 如何将默认参数添加到asp.net mvc中的属性路由