JsonArray.Parse(…) error

前端 未结 2 1174
时光说笑
时光说笑 2021-01-01 05:53

I am developing a news-app for Windows 8 (in C#, XAML). Unfortunately I encountered a strange error after downloading a JSON-Feed (validated with http://jsonlint.com/) async

相关标签:
2条回答
  • 2021-01-01 06:25

    I was able to run your code after a small modification. The byte order mark of the UTF8 string seems to triggers a problem with JsonArray.Parse() from Windows.Data.Json.

    A way to solve it without using additional encoding is to replace the BOM character after ReadAsStringAsync(), e.g.

    result = result.Replace('\xfeff', ' ');
    

    or better

    if (result.Length > 1 && result[0] == '\xfeff'){
        result = result.Remove(0, 1);
    }
    
    0 讨论(0)
  • 2021-01-01 06:32

    I was able to download and parse the result fine using this:

    static async Task<JsonValue> DownloadJsonAsync(string url)
    {
        var client = new HttpClient();
        client.MaxResponseContentBufferSize = 1024 * 1024;
        var data = await client.GetByteArrayAsync(new Uri(url));
        var encoding = Encoding.UTF8;
        var preamble = encoding.GetPreamble();
        var content = encoding.GetString(data, preamble.Length, data.Length - preamble.Length);
        var result = JsonValue.Parse(content);
        return result;
    }
    

    The BOM in the response wasn't handled correctly apparently which resulted in having a '\xfeff' character in the beginning killing the parser. Stripping off the preamble and parsing reads fine. Otherwise parsing it as-is throws a FormatException with the message: Encountered unexpected character 'ï'..

    0 讨论(0)
提交回复
热议问题