简体   繁体   English

在WinRT中解析C#中的JSON

[英]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. 我正在开发一个适用于Windows 8的应用程序。我正在尝试通过JSON对Twitter进行搜索。 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 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? 我的问题是,ASCIIEncoding类似乎不存在于WinRT框架中:(。我看到UTF8可用,但是,我不确定如何直接使用UTF8类。有人可以告诉我如何?

Thank you, 谢谢,

For deserializing JSON in .NET (both full .NET and WinRT) I always recommend JSON.NET . 为了反序列化.NET中的JSON(完整的.NET和WinRT),我总是推荐使用JSON.NET It's much easier than DataContractJsonSerializer or any other out of the box solution. 它比DataContractJsonSerializer或任何其他开箱即用的解决方案容易得多。 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: 您只需要一个对象模型(使用json2csharp生成它)和几行代码:

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. 我写了一篇更广泛的文章,展示了前一段时间WinRTJSON解析的不同可能性。

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 ). 您可以尝试使用Windows.Data.Json命名空间进行反序列化( 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: 要获得你的json,你可以使用这样的东西:

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). 只需用Encoding.UTF8替换ASCIIEncoding.UTF8 - 它们本质上是同一个对象(静态UTF8属性在桌面框架上的基本Encoding类中定义)。 And that's available in W8 metro apps. 这在W8 metro应用程序中可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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