简体   繁体   中英

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.

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

JavaScriptSerializer is not available for UWP Apps as it seems.

DataContractJsonSerializer can't convert to char aswell.

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. 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 ).

In your case you indicate you want a string, so you could use ReadAsStringAsync() .

You need GetResponse....

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

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