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!
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.
or better
I was able to download and parse the result fine using this:
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 aFormatException
with the message:Encountered unexpected character 'ï'.
.