Parsing JSON from C# in WinRT - c#

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.

Related

How to show Json string data in list view for multiple columns in Xamarin.android using C#?

I am trying to make an android app using Xamarin. As I am new to Xamarin, I am facing an issue i.e How to display JSON string data in to ListView or in to grid.
I am using WebApi to fetch data from database. Webapi returns string that is-
[{"QuestionId":2,"Question1":"4,8,12 Which Digit is Greatest?","Answer":"12"}]
Method I am using in android application is-
private string QuestionList()
{
var url = HttpWebRequest.Create(string.Format(#"url"));
url.ContentType = "application/json";
url.Method = "GET";
string tempdata = string.Empty;
using (HttpWebResponse response = url.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
Console.Out.WriteLine("error", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
if (string.IsNullOrWhiteSpace(content))
{
Console.Out.WriteLine("response");
}
else {
Console.Out.WriteLine("response", content);
tempdata = content;
}
}
}
return tempdata;
}
It is returning Json string on my android device. Now I want to show this data in list or in a grid with multiple columns.
First you have to use the Newtonsoft nuget package to convert this JSON string.
http://www.newtonsoft.com/json
You can use the website json2csharp. Just provide the json string in the input and click in generate, it will be create the corresponding class for you.
After that you can use the xamarin documentation about list view in android.
https://developer.xamarin.com/guides/android/user_interface/working_with_listviews_and_adapters/part_2_-_populating_a_listview_with_data/
This tutoriel will provide you some code examples to create a list view.
You will have to create a custom adapter if you want to "customize" your listview but it's quite easy to follow a tutorial about that.
To finish, I give you this last link :
https://www.youtube.com/watch?v=zZHLHrkvUt0
This is the link of a youtube channel with very good tutorials about android with xamarin. When I started using this technologie, I follow a lot of this videos.
If you need more help, don't hesitate to post a more advanced code.
Hope this can help you.

Visual C# make web request like python's

i'm having a little piece of python code which makes a web request using the urllib2 as you can se below
import json
import urllib2
urlRequest = urllib2.Request('<link>')
urlRequest.add_header('Content-Type', 'application/json')
urlRequest.add_header('RegistrationToken', '<token>')
data = {
'content': '<c>',
'messagetype': 'RichText',
'contenttype': 'text',
'id': '<id>'
}
urllib2.urlopen(urlRequest, json.dumps(data))
As i was trying to do it in C# i came across the following problems
how to i send the data
how do i add the headers?
After googling for a while i managed to write this code:
var request = (HttpWebRequest)WebRequest.Create(url_input.Text);
request.ContentType = "application/json";
request.Headers["RegistrationToken"] = rtoken_input.Text;
request.GetResponse();
I managed to deal with the headers part but the question on the data still remains. Also what is the best way to json encode something?
Anyone who knows what to do?
If you are after serializing the POST data to a JSON payload there are few options.
1) System.Web.Helpers.Json.Encode MSDN Link
2) using the JSON.NET library Link
As for your attempt on converting python to C# you are on the correct track.
Refer to this link
Alternatively you could make use of the WebClient class MSDN Link
Refer to this link as well
Pseudo code
var client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("RegistrationToken", "<token>");
string response = client.UploadString("<link>", "<json string>");

WebClient class doesn't exist in Windows 8

I want to use a HTTP webservice, and I've already developed an app for wp7.
I use the WebClient class, but I can not use it for windows 8 ("error: type or namespace can not be found").
What else can I use?
Can you provide me a sample of code?
Does Microsoft have a site to help when a namespace don't exist?
Option 1 : HttpClient if you don't need deterministic progress notification this is what you want use. Example.
public async Task<string> MakeWebRequest()
{
HttpClient http = new System.Net.Http.HttpClient();
HttpResponseMessage response = await http.GetAsync("http://www.example.com");
return await response.Content.ReadAsStringAsync();
}
Option 2: When you need progress notifications you can use DownloadOperation or BackgroundDownloader. This sample on MSDN is a good start.
Option 3: Since you mentioned web service and if it is returning XML you can use XmlDocument.LoadFromUriAsync which will return you an XML document. Example
public async void DownloadXMLDocument()
{
Uri uri = new Uri("http://example.com/sample.xml");
XmlDocument xmlDocument = await XmlDocument.LoadFromUriAsync(uri);
//do something with the xmlDocument.
}
When you are developing for metro .Net framework will be limited compared to the desktop version. If you see namespace not found error it is usually due to this fact. This link on the MSDN has the list of namespaces, classes available for metro.

How Do I De-Serialize JSON From the Facebook Graph API?

So i'm trying to de-serialize the JSON returned from the Graph API OAuth Token call.
The JSON looks like this:
"[{\"access_token\":\"bunchofjsondatablahblah",\"expires\":9999}]"
I'm trying to de-serialize it (using the DataContractJsonSerializer class) into this object:
[DataContract]
internal class FacebookOAuthToken
{
[DataMember]
internal string access_token;
[DataMember]
internal string expires;
}
Here's how im (trying) to do it:
FacebookOAuthToken token;
using (Stream responseStream = (response.GetReponseStream()))
{
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(FacebookOAuthToken));
token = (FacebookOAuthToken)json.ReadObject(responseStream);
}
This technique is based on this article from MSDN.
However, the properties of token are always null.
Whereas if i do responseStream.ReadToEnd(), it's all fine (returns the above JSON) - which means its not a problem with the actual HTTP request/response, i'm just not deserializing it properly.
What am i doing wrong?
Okay so it turns out i was using the wrong Graph API URL (so it seems).
This is the problem with the Facebook API Documentation, its all over the place and different threads (google, stack overflow) say different ways how to do things.
I changed to the URL https://graph.facebook.com/oauth/access_token?{0} instead of https://graph.facebook.com/oauth/exchange_sessions?{0} and it now returns a basic string (non-JSON).
So it doesnt need to be serialized at all.
Still, some people might have the same problem as me above, in that case im not sure how to solve.
I'm now using the method defined here.
If I interpret the JSON string correctly it represents a collection of FacebookOAuthToken items with one single instance in it and not just a single token.
Maybe that is why your deserialization did not work.

Parse JSON in .NET runtime

I want to get some response from WebServer.
The returning data looks like this:
[[3014887,"string1 string","http://num60.webservice.com/u3014887/b_c9c0625b.jpg",0],
[3061529,"string2 string","http://num879.webservice.com/u3061529/b_320d6d36.jpg",0],
[7317649,"string3 string","http://num1233.webservice.com/u7317649/b_a60b3dc2.jpg",0],
[12851194,"string4 string","http://num843.webservice.com/u12851194/b_4e273fa4.jpg",0],
[15819606,"string5 string","http://num9782.webservice.com/u15819606/b_66333a8f.jpg",0],
[15947248,"string6 string","http://num1500.webservice.com/u15947248/b_920c8b64.jpg",0]]
I think is in the JSON format, but I couldn't parse it in my .Net WinForm application.
Can you provide some advise or exampe how to do that.
I googled about JSON.NET library, DataContractJsonSerializer class, but I couldn't understand how to glue it all together with the response's data type...
If you want to parse JSON, then the JSON.net library is the place to be.
You can use it like this:
var json = #"[[3014887,""string1 string"",""http://num60.webservice.com/u3014887/b_c9c0625b.jpg"",0],
[3061529,""string2 string"",""http://num879.webservice.com/u3061529/b_320d6d36.jpg"",0],
[7317649,""string3 string"",""http://num1233.webservice.com/u7317649/b_a60b3dc2.jpg"",0],
[12851194,""string4 string"",""http://num843.webservice.com/u12851194/b_4e273fa4.jpg"",0],
[15819606,""string5 string"",""http://num9782.webservice.com/u15819606/b_66333a8f.jpg"",0],
[15947248,""string6 string"",""http://num1500.webservice.com/u15947248/b_920c8b64.jpg"",0]]";
var array = JArray.Parse(json);
foreach (var token in array)
{
Console.WriteLine(token[0]);
}
This way I could read the contents of your array.
There is JSON(De)serialization in the WCF namespace (Windows Communication Support for AJAX Integration and JSON
)
there is also the very popular (more powerful) JSON (de)serialization library JSON.Net

Categories