Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonArray.Parse(...) error

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!

like image 958
casaout Avatar asked Jun 19 '26 15:06

casaout


1 Answers

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

like image 166
Jeff Mercado Avatar answered Jun 21 '26 04:06

Jeff Mercado