简体   繁体   English

使用Visual Studio 2017将C#JSON转换为字符串

[英]C# JSON to String with Visual Studio 2017

I'm building an UWP App in Visual Studio 2017 and I want to convert a JSON-Response from Office365 REST API into a string, to Display it in the XAML. 我正在Visual Studio 2017中构建UWP应用,我想将Office365 REST API的JSON响应转换为字符串,以在XAML中显示它。

HttpClient client2 = new HttpClient();
var token2 = await AuthenticationHelper.GetTokenHelperAsync();
client2.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
HttpResponseMessage eventresponse = await client2.GetAsync(new Uri("https://outlook.office.com/api/v2.0/me/calendarview?startDateTime=2017-01-01T00:00:00&endDateTime=2017-04-05T12:00:00"));

I can't get json.net, i guess it is not compatible. 我无法获取json.net,我认为它不兼容。 I tried the following: 我尝试了以下方法:

using (Stream stream = eventresponse)
{
    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
    String responseString = reader.ReadToEnd();
}

But I can't convert HttpResponseMessage into System.IO.Stream. 但是我无法将HttpResponseMessage转换为System.IO.Stream。

JavaScriptSerializer is not available for UWP Apps as it seems. 看起来JavaScriptSerializer不适用于UWP Apps。

DataContractJsonSerializer can't convert to char aswell. DataContractJsonSerializer也无法转换为char。

So im running out of possible Solutions/overseeing a big mistake I made. 所以即时通讯用尽了可能的解决方案/监督了我犯的一个大错误。

change 更改

using (Stream stream = eventresponse)
{
    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
    String responseString = reader.ReadToEnd();
}

to

string responseString = await eventresponse.Content.ReadAsStringAsync();

Or with stream like your code.. 或使用类似您的代码的流。

if (eventresponse.IsSuccessStatusCode)
{
    using (Stream stream = await eventresponse.Content.ReadAsStreamAsync())
    {
        using (StreamReader reader = new StreamReader(stream))
        {
            var responseString = reader.ReadToEnd();
        }
    }
}

As far as the HttpResponseMessage is concerned, the response body is a series of bytes. HttpResponseMessage而言,响应主体是一系列字节。 It is indifferent to what they actually represent. 不管它们实际代表什么。

You can access these bytes through the Content member and use methods on that member to direct how they the bytes should be processed ( including accessing them as a Stream ). 您可以通过Content成员访问这些字节,并使用该成员上的方法来指示应如何处理这些字节( 包括以Stream的形式访问它们 )。

In your case you indicate you want a string, so you could use ReadAsStringAsync() . 在您的情况下,您指示需要一个字符串,因此可以使用ReadAsStringAsync()

You need GetResponse.... 您需要GetResponse...。

Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
txtBlock.Text = readStream.ReadToEnd();

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

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