JsonArray.Parse(…) error

2020-02-26 13:07发布

问题:

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/) asynchronously. The download succeeds and then I want to parse the result: var items = Windows.Data.JsonArray.Parse(result);.

When I run the code I get the following error:

Invalid character at position 0. and Invalid JSON string.

Json.JsonArray is a new Library from Microsoft. I also tried Newtonsoft's JSON-library with the same errors. What am I doing wrong?

This is the full code:

// Retrieve recipe data from Azure
var client = new HttpClient();
client.MaxResponseContentBufferSize = 1024*1024; // Read up to 1 MB of data
var response = await client.GetAsync(new Uri("http://contosorecipes8.blob.core.windows.net/AzureRecipes"));
var result = await response.Content.ReadAsStringAsync();

// Parse the JSON recipe data
var recipes = JsonArray.Parse(result.Substring(1, result.Length - 1));

This code snippet is from a Microsoft Hands-On Lab (Contoso CookBook). I also tried it without the "[" and "]" in the source (with no effect)...

Thank you!

回答1:

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


回答2:

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 'ï'..