为 HttpClient Post 方法准备 Json 对象

preparing Json Object for HttpClient Post method

我正在尝试为 Post 方法准备一个 JSON 负载。服务器无法解析我的数据。我的值上的 ToString() 方法无法将其正确转换为 JSON,能否请您提出正确的方法。

var values = new Dictionary<string, string>
{
    {
        "type", "a"
    }

    , {
        "card", "2"
    }

};
var data = new StringContent(values.ToSttring(), Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
var response = client.PostAsync(myUrl, data).Result;
using (HttpContent content = response.content)
{
    result = response.content.ReadAsStringAsync().Result;
}

https://www.newtonsoft.com/json 使用这个。 已经有很多类似的话题。 Send JSON via POST in C# and Receive the JSON returned?

您需要先使用 JsonConvert.SerializeObject

手动序列化对象
var values = new Dictionary<string, string> 
            {
              {"type", "a"}, {"card", "2"}
            };
var json = JsonConvert.SerializeObject(values);
var data = new StringContent(json, Encoding.UTF8, "application/json");

//...code removed for brevity

或者根据您的平台,在 HttpClient 上使用 PostAsJsonAsync 扩展方法。

var values = new Dictionary<string, string> 
            {
              {"type", "a"}, {"card", "2"}
            };
var client = new HttpClient();
using(var response = client.PostAsJsonAsync(myUrl, values).Result) {
    result = response.Content.ReadAsStringAsync().Result;
}

values.ToString() 不会创建有效的 JSON 格式字符串。

我建议您使用 JSON 解析器,例如 Json.NetLitJson 将您的词典转换为有效的 json 字符串。这些库能够使用反射将通用对象转换为有效的 JSON 字符串,并且比手动序列化为 JSON 格式更快(尽管如果需要,这是可能的)。

请在此处查看 JSON 字符串格式定义(如果您希望手动序列化对象),以及底部的第 3 方库列表:http://www.json.org/