首页 > 解决方案 > C# - 如何使用 FormUrlEncodedContent 更新 JSON 正文中的嵌套值?

问题描述

我需要使用FormUrlEncodedContent对 JSON 包进行基本更新

目前,我只能在父级分配值。

例如,这是将通过 API 发送的 JSON 包。

[
    {
        "id": 29519,
        "first_name": "xxxx",
        "last_name": "xxx",
        "billing": {
            "address_1": "xxxx",
            "address_2": "xxxx"
        }
   }
]

目前,我只能使用以下代码更新first_namelast_name值:

var UpdateCustomerAPI = "https://example.com/api/";
var UpdateCustomer_JSON = new FormUrlEncodedContent(new[]
{
   new KeyValuePair<string,string>("first_name", CustomerFirstName.Text),
   new KeyValuePair<string,string>("last_name", CustomerLastName.Text)
});
var httpClient = new HttpClient();
var response = httpClient.PutAsync(UpdateCustomerAPI, UpdateCustomer_JSON);

如何使用FormUrlEncodedContent更新billing:address_1billing:address_2中的值?

标签: c#jsonxamarin.forms

解决方案


你不知道:https ://docs.microsoft.com/en-us/dotnet/api/system.net.http.formurlencodedcontent?view=netcore-3.1

使用 application/x-www-form-urlencoded MIME 类型编码的名称/值元组的容器。

来自https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST

application/x-www-form-urlencoded:键和值编码在键值元组中,用'&'分隔,键和值之间有'='。

您没有将 json 文件放入服务器。如果您想使用它,那么您应该执行以下操作:

var UpdateCustomer_JSON = new FormUrlEncodedContent(new[]
{
   new KeyValuePair<string,string>("billing_address_1", CustomerBillingAddress.Text),
});

如果你想发布一个 json 文件,那么你应该使用application/json我的类型并使用这样的东西:

var data = JsonConvert.SerializeObject(customerData);

推荐阅读