【问题标题】:Post a Json string in Xamarin在 Xamarin 中发布 Json 字符串
【发布时间】:2019-04-23 12:41:28
【问题描述】:

在我的应用程序中,我以这种方式将 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 格式。我哪里错了。任何帮助将非常感激。 数据是一个字符串。

【问题讨论】:

  • 你能得到你的服务器收到的东西吗?

标签: c# json xamarin xamarin.ios


【解决方案1】:

通过调用

 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);

//...

【讨论】:

  • 试过了,还是不行。我不知道出了什么问题。
  • { "hasError": true, "error": { "code": 601, "developer_message": "input not is JSON format", "user_message": "显示给用户的错误信息" } }
  • 这是服务器返回的内容。如果 hasError 为 false,我会从服务器取回 encryptedData。
猜你喜欢
  • 2018-05-08
  • 2017-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 1970-01-01
  • 2016-08-02
相关资源
最近更新 更多