【问题标题】:I get \r\n and \ in my response Xamarin, how to avoid it?我在回复 Xamarin 中得到 \r\n 和 \,如何避免它?
【发布时间】:2019-06-10 19:52:46
【问题描述】:

我使用 xamarin 发送 RQ 并解析 JSON 响应,但在我的响应中,我在每个 " 之前得到 \r\n\

我知道一些编辑器(如 NuSphere(PhPed))可以选择禁用添加这些符号,但我找不到任何方法在 Xamarin 中删除它。

    public async Task Post_RequestAsync()
    {
        var request = new HttpRequestMessage();
        request.RequestUri = new Uri(GET_RQ_ENDPOINT);
        request.Method = HttpMethod.Post;
        request.Headers.Add("Accept", "application/json");
        var client = new HttpClient();
        HttpResponseMessage response = await 
      client.SendAsync(request).ConfigureAwait(continueOnCapturedContext: 
false);

        if (response.StatusCode == HttpStatusCode.OK)
        {
            string content = await response.Content.ReadAsStringAsync();

            Console.WriteLine(content);
        }
        else
        {
            Console.WriteLine("BAD!");
        }

        await Task.Delay(1);

    }

这是我用来获得响应的方法。我做了一些修剪和删除\r\n,但有什么优雅的解决方案可以删除它们吗?

【问题讨论】:

标签: c# xamarin newline


【解决方案1】:

首先,我建议你在服务器端处理这些问题,通常发生在数据字符串前后有空格的情况下。如果你在服务器端处理,就简单了,一劳永逸。当你得到响应时,你不必做任何额外的处理。

当然,如果你不能从服务器端处理它,你只能通过像这样替换正则表达式来删除所有需要的字符:

string content = await response.Content.ReadAsStringAsync();
var result = Regex.Replace(content, @"\t|\n|\r", "");

另外:VS没有去除这些字符的功能。这个问题与我们在服务器端和客户端的代码有关。

【讨论】:

    【解决方案2】:

    尝试使用正则表达式

    string content = await response.Content.ReadAsStringAsync();
    var result = Regex.Replace(content, @"\t|\n|\r", "");
    

    这应该删除所有需要的字符。

    【讨论】:

    • 是的,我做到了,但是 VS2019 中是否有删除添加这些字符的选项?我知道它可以在 NuSphere 中完成。
    • 根据您向 API 请求数据的代码。您希望 VS 如何摆脱这些角色? VS 是 IDE,我们在谈论代码
    猜你喜欢
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    相关资源
    最近更新 更多