简体   繁体   中英

Parsing JSON from C# in WinRT

I am working on an app for Windows 8. I'm trying to do a search against Twitter via JSON. In an attempt to accomplish this, I was using the following blog post for reference. http://blogs.microsoft.co.il/blogs/bursteg/archive/2008/11/26/twitter-api-from-c-searching.aspx

My problem is, the ASCIIEncoding class doesn't seem to exist in the WinRT framework :(. I saw that UTF8 is available, however, I'm not sure how to use the UTF8 class directly. Can someone please show me how?

Thank you,

For deserializing JSON in .NET (both full .NET and WinRT) I always recommend JSON.NET . It's much easier than DataContractJsonSerializer or any other out of the box solution. And as you can see in the code below, you don't need to define the encoding as they do in the example you provide.

All you need is an object model (use json2csharp to generate it) and a few lines of code:

HttpResponseMessage response = await HttpClient.GetAsync(someUri);
if (response.StatusCode == HttpStatusCode.OK)
{
    string responseString = await response.Content.ReadAsStringAsync();
    // parse to json
    resultItem = JsonConvert.DeserializeObject<T>(responseString);
}

I wrote a more extensive post that shows the different possibilities of JSON parsing in WinRT some time ago.

You can try to use Windows.Data.Json namespace to deserialize ( http://msdn.microsoft.com/en-us/library/windows/apps/windows.data.json(v=VS.85).aspx ). To get your json you can use something like this:

HttpResponseMessage response = await client.GetAsync(url);
string responseText = await response.Content.ReadAsStringAsync();

Just replace ASCIIEncoding.UTF8 with Encoding.UTF8 - they're essentially the same object (the static UTF8 property is defined in the base Encoding class on the desktop framework). And that's available in W8 metro apps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM