【问题标题】:Passing symbols inside Json through HttpWebRequest通过 HttpWebRequest 在 Json 中传递符号
【发布时间】:2018-11-13 09:57:45
【问题描述】:

我尝试使用以下方法以 Json 格式将消息传递给 MS Flow,但是一旦传递任何符号(如“),我就会收到错误,因为符号被识别为代码。

public static bool notification(string customer, string comment)
    {
        try
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("my msflow link goes here");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "{ \"customer\":\"" + customer + "\",\"comment\":\"" + comment + "\"}";

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();

            }

            return true;
        }
        catch (Exception)
        {
            return false;
        }

    }

【问题讨论】:

  • 像这样手动创建 JSON 是个坏主意 - 正如您所发现的,它容易出现愚蠢的语法错误,以及某些字符的解释问题。而是创建一个 C# 对象,然后使用 JSON.NET 之类的东西对其进行序列化。这样,序列化程序将处理数据中的任何特殊字符并适当地转义/编码它们。

标签: c# json httpwebrequest symbols


【解决方案1】:

尝试使用JSON.NET 在代码中序列化您的对象,如下所示:

string json = JsonConvert.SerializeObject(<your object>);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-25
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多