在我的应用程序中,我以这种方式将 json 字符串发布到服务器:
string url = "my/url";
HttpClient newClient = new HttpClient();
string contentType = "application/json";
JObject json = new JObject
{
{ "id", "id" },
{ "apiKey", "apiKey" },
{ "EncryptedData", Data }
};
var jon = JsonConvert.SerializeObject(json);
var content = new StringContent(jon, Encoding.UTF8, contentType);
var TaskPostAsync = await newClient.PostAsync(url, content);
if (TaskPostAsync.IsSuccessStatusCode)
{
var contentString = await TaskPostAsync.Content.ReadAsStringAsync();}
我收到的回复是它不是 Json 格式。我哪里错了。任何帮助将非常感激。 数据是一个字符串。
最佳答案
通过调用
var jon = JsonConvert.SerializeObject(json);
你正在序列化它两次。
JObject
已经是 JSON,所以您需要做的就是调用 .ToString
来获取 JSON
//...
JObject json = new JObject
{
{ "id", "id" },
{ "apiKey", "apiKey" },
{ "EncryptedData", Data }
};
var content = new StringContent(json.ToString(), Encoding.UTF8, contentType);
//...
引用 Write JSON text with JToken.ToString
另一种选择是使用匿名对象然后序列化它
//...
var model = new {
id = "id",
apiKey = "apiKey",
encryptedData = Data
};
var json = JsonConvert.SerializeObject(model);
var content = new StringContent(json, Encoding.UTF8, contentType);
//...
关于c# - 在 Xamarin 中发布 Json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53403702/