Parse JSON in .NET runtime - c#

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

Related

Deserializing a byte[] from C# Tool in Node.js

I have inherited a C# tool that sends a serialized byte array of meeting data to an online calendar application. The online calendar uses a node.js API. My problem is that the serialized byte array is not getting parsed correclty by node.js (IE, in express the req.body object is empty). I am look for either a way to send the data so it can be parsed by Node.js, or a parser in Node.js that can handle c# byte arrays. It is JSON formatted. Here is the code that sends the request:
string json = JsonConvert.SerializeObject(reallyPost, Formatting.None);
byte[] postThisz = Encoding.ASCII.GetBytes(json);
byte[] response = wc.UploadData(siteUrl, postThisz);
At the moment I'm simply trying to log the data. The route is caught here:
app.post('/remotePost', api.remotePost);
which uses this controller:
module.exports.remotePost = function (req, res) {
console.log(req);
console.log(req.body);
sendJsonResponse(res, 200, "remote posted.");
};
The req.body gets populated by my parsing middleware:
app.use(bodyParser.json());
However this cannot handle the byte array sent by the C# program. I can solve this either by finding a parser that will handle the C# POST correctly (byte[] type), or finding a C# module that can make a post containing something of the format that JSON.stringify() returns.
It's advisable to change the encoding to utf8
Encoding.UTF8.GetBytes(json);
Then, you should also set the appropriate headers before upload
wc.Headers.Add("Content-Type", "application/json; charset=utf8");

How to receive and process JSON data from a URL in C # Web Service?

How to receive and process JSON data from a URL in C# Web Service ?
I have a Web Service in C# and I must receive JSON data from a given URL.
Someone can give me an example of code that allows to receive JSON data and convert them into an object that allows me to treat the data for other operations.
You can take a look at http://james.newtonking.com/json for parsing the json file (you can also download it from a nuget package).
So after you install it your code will look like this:
string url = "http://example.com/MethodThatReturnsJson";
using (WebClient client = new WebClient())
{
string webServiceJsonString = client.DownloadString(url);
YourObject yourObject = JsonConvert.DeserializeObject<YourObject>(webServiceJsonString);
}

FormatExcpetion from Azure Webjobs Host

Understand this is pre-release :)
When trying to use QueueInput in Azure WebJobs and sticking the hex string of a hash in the message.
public System.Guid GetOwner(CloudQueueMessage msg)
Looking at ilspy seems like it is trying to parse out $AzureJobsParentId and the JSON parser is throwing the exception I can get around it by encoding my hash in a JSON snippet but I'd prefer not to. Is this a known bug?
[QueueInput] will normally use JSON.Net to deserialize the queue message payload to the parameter type. So if the queue message is not JSON, you'll get a exception (which should then be wrapped in something more friendly).
You can also work around it by using a string parameter with [QueueInput], like:
public static void Function([QueueInput] string testqueue)
{
}
For string parameter, the SDK will give you the QueueMessage.AsString directly, without any JSON serialization.
FYI, $AzureJobsParentId is a special field placed on json payloads that identifies which function instance enqueued a message. This gets used when you enqueue a message with [QueueOutput]. You can then view that relationship in the SDK dashboard (http://blogs.msdn.com/b/jmstall/archive/2014/01/27/getting-a-dashboard-for-local-development-with-the-webjobs-sdk.aspx)

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.

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.

Categories