我正在尝试解析在 Post 请求中收到的 JSON。
JSON如下。它必须不知道有多少记录或字段被称为什么。但是当我通过 postman 发送时,联系人变量总是空的。我把它扔到的类(class)有问题吗?
{
"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;
...
}
关于c# - 需要解析通过 Post 请求传入的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57465372/