C#-如何从更高级的JSON生成FormUrlEncodedContent?

时间:2019-03-15 21:29:33

标签: c# .net json http

我没有用这个http请求正文json制作FormUrlEncodedContent

{
    "number": 123456,
    "names": {
        "firstName": "a",
        "secondName": "b",
        "age": 10
    }
}

我可以像这样从“一级” json制作它:

 FormUrlEncodedContent content = new FormUrlEncodedContent(
            new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("number", "123"),
                new KeyValuePair<string, string>("name", "John")
            });

但是我真的不知道如何提高下一个水平。我要POST请求。

更新:

我用它来连接NodeJs服务器。有此控件:

const {number, names} = this.request.body;

    if (!number|| !names|| !names.firstName|| !names.secondName|| !names.age)

1 个答案:

答案 0 :(得分:0)

如果将其发送到ASP.NET MVC服务或WebAPI服务,则标准模型绑定程序可以反序列化发送的请求,如下所示:

FormUrlEncodedContent content = new FormUrlEncodedContent(
            new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("number", "123"),
                new KeyValuePair<string, string>("name", "John"),
                new KeyValuePair<string, string>("names.firstName", "a"),
                new KeyValuePair<string, string>("names.secondName", "b"),
                new KeyValuePair<string, string>("names.age", "10"),
            });

我经常看到的另一种约定(不适用于ASP.NET MVC或WebAPI中的默认模型绑定程序)是做这样的事情:

FormUrlEncodedContent content = new FormUrlEncodedContent(
            new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("number", "123"),
                new KeyValuePair<string, string>("name", "John"),
                new KeyValuePair<string, string>("names[firstName]", "a"),
                new KeyValuePair<string, string>("names[secondName]", "b"),
                new KeyValuePair<string, string>("names[age]", "10"),
            });