c# - 在 Xamarin 中发布 Json 字符串

标签 c# json xamarin xamarin.ios

在我的应用程序中,我以这种方式将 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/

相关文章:

c++ - 如何使用 boost 从 C++ 中的 json 中读取枚举?

ios - Xamarin iOS : how to call NSSetUncaughtExceptionHandler method?

c# - 微调器 XAMARIN.ANDROID

c# - 拖放时吞下异常

c# - 具有两个 GET 操作的 WebApi Controller

json - Apache Spark : Convert column with a JSON String to new Dataframe in Scala spark

c# - 在 Xamarin.Forms 中绑定(bind) ToolbarItem 单击

c# - 从 PC 以编程方式访问 Android 设备上的文件

c# - 用 C# 编写可升级的软件及其升级

json - Python json加载错误: JSONDecodeError: Expecting value