Parse Google JSON response in VB.NET - asp.net

I'm trying to parse the JSON response form google. This is what I currently have:
Dim x As New System.Web.Script.Serialization.JavaScriptSerializer
Dim gJson As String = ""
Dim wClient As New WebClient
wClient.Proxy = System.Net.HttpWebRequest.DefaultWebProxy
gJson = wClient.DownloadString("https://www.googleapis.com/...alt=json")
Dim results As gResponseClass = x.Deserialize(Of gResponseClass)(gJson)
gResponseClass as follows here: PasteBin
I keep getting the following exception thrown:
Invalid object passed in, member name expected. (6678): .... *the json response here* ...
Is there any blatant problems or solutions I could implement?
EDIT :
The JSON response from google: JSON Response
EDIT
Just for continuation purposes: the erros is cased indeed by the "": inside the pagemap node on facebook pages. I have resorted to calling a cleanup function as follows:
json = json.Replace(""""":", """page_id"":")
Return json
If anyone has a better way, please let me know!
Thanks again.

It looks like this is the bit of the JSON it's having trouble with:
"": [
{
"page_id": "66721388277"
}
],
I'm not a JSON expert, but I can see why it might be surprised by that. As I mentioned, it can be parsed by Json.NET (at least as a JObject) so you might want to try using that instead.
Original answer, still relevant
The DeserializeObject method specifies:
This deserialization method does not try to cast the root of the object graph to a specific type, as with the Deserialize method.
So I'd be surprised if it managed to cast to gResponseClass anyway. Have you tried using the Deserialize method instead?
(I'd have expected a compile-time error to be honest - do you have option strict and option explicit on?)
That may well not be the problem you're facing, but it's the first thing I'd look at anyway :) The JSON parses fine with JSON.NET.

Related

BizTalk ExecuteReceivePipeline can't accept XmdlDocument parameter

I'm trying to call a receive pipeline from the orchestration in order to catch any type of flatfile_to_xml error.
After searching for tutorials, the process seemed quite easy.
Added the libraries, created my inputMsg of type xmlDocument to inglobe any non-Xml payload (in my case the content of my file.txt) and created an atomic scope containing an expression for:
Microsoft.XLANGs.Pipeline.XLANGPipelineManager
.ExecuteReceivePipeline(typeof(namespace.pipelineName), msgIN);
Too bad I get that ExecuteReceivePipeline can't accept a XmlDocument while it accepts only a Microsoft.XLANGs.BaseType.XLANGMessage).
Cannot connvert from 'System.Xml.XmlDocument' to 'Microsoft.XLANGs.BaseTypes.XLANGMEssage'
Why this, and how can I achieve what I'm trying to achieve?
You have to use a Message variable of type XmlDocument.
It look like you're using a variable of type XmlDocument.
Ok, now it's working and i'm not sure why.
At first the msgIN of type XmlDocument wasn't accepted as a valid parameter.
I then created a msgType of type XmlDocument, and assigned it as the type of the message, so that calling:
ExecuteReceivePipeline(typeof(namespace.pipelineName), msgIN)
would be valid. after many rebuild and deploy i switched back to msgIn as XmlDocument... and it worked as intended...
I don't get it, but it's not the first time that a rebuild or a close-and-reopen of VS solved my preblems.
Thanks for those who found the time to answer!

Elm - retrieving string via get request

I am trying to make a get request to retrieve a string
When I use
retrieve : Task.Task Http.Error String
retrieve = getString "http://api.endpoint.com"
everything works fine.
On the other hand if I use
retrieve : Task.Task Http.Error String
retrieve = get Json.Decode.string "http://api.endpoint.com"
the http request gets done, but the chained tasks are not executed.
My question is: what is the difference between the two approaches above? Am I doing something wrong with the second one? How to debug it?
getString returns the response of the get request as a String. get take a JSON decoder and runs that over the response of the get request. So if you provide Json.Decode.string, it will expect the response to be have a Json encoded string in it. So it expects extra double quotes in the response.
If your http request fails the best way to debug is to look at what kind of error you get. In this case you'll probably get an UnexpectedPayload because the request succeeds, but the decoder fails.

Backslashes in JSON string

I'm not familiar with this format:
{"d":"{\"Table\":[{\"pCol\":12345,\"fCol\":\"jeff\",\"lCol\":\"Smith\",\"dId\":1111111,\"tDate\":\"\\/Date(1153033200000-0700)\\/\"}]}"}
I'm using Newtonsoft to serialize my DataSet that I'm returning from my ASP.Net webservice. The above JSON string is what Firebug is returning. I have checked this JSON using jsLint and it is good.
In firebug I see the JSON data and my first alert('success'); However when I try to alert(msg.d.Table); I get nothing. Not an alert box or an error in Firebug... I think it has something to do with these backslashes... But I'm not sure.
Any ideas?
Those backslashes are escape characters. They are escaping the double quotes inside of the string associated with d. The reason you cant alert msg.d.Table is because the value of d is a string. You have to use JSON.parse to parse that JSON string into a JSON object.
Then, you have to convert Table back to a string to alert it.
Something like this:
var dObj = JSON.parse(msg.d);
alert(JSON.stringify(dObj.Table, null, 2));
The ASP.Net webservice is already serializing the return value to JSON. (in a d property for security reasons)
When you return pre-serialized JSON data, it thinks you're giving it a normal string, and proceeds to serialize the string as JSON.
Therefore, you get a JSON object with a d property that contains the raw JSON string (with correctly escaped quotes) that you returned.
You should return the raw object and let ASP.Net serialize it for you instead of serializing it yourself.

parsing simple xml with jquery from asp.net webservice

I'm breaking my head over this for a while now and I have no clue what I do wrong.
The scenario is as followed, I'm using swfupload to upload files with a progressbar
via a webservice. the webservice needs to return the name of the generated thumbnail.
This all goes well and though i prefer to get the returned data in json (might change it later in the swfupload js files) the default xml data is fine too.
So when an upload completes the webservice returns the following xml as expected (note I removed the namespace in webservice):
<?xml version="1.0" encoding="utf-8"?>
<string>myfile.jpg</string>
Now I want to parse this result with jquery and thought the following would do it:
var xml = response;
alert($(xml).find("string").text());
But I cannot get the string value. I've tried lots of combinations (.html(), .innerhtml(), response.find("string").text() but nothing seems to work. This is my first time trying to parse xml via jquery so maybe I'm doing something fundemantally wrong. The 'response' is populated with the xml.
I hope someone can help me with this.
Thanks for your time.
Kind regards,
Mark
I think $(xml) is looking for a dom object with a selector that matches the string value of XML, so I guess it's coming back null or empty?
The First Plugin mentioned below xmldom looks pretty good, but if your returned XML really is as simply as your example above, a bit of string parsing might be quicker, something like:
var start = xml.indexOf('<string>') + 8;
var end = xml.indexOf('</string>');
var resultstring = xml.substring(start, end);
From this answer to this question: How to query an XML string via DOM in jQuery
Quote:
There are a 2 ways to approach this.
Convert the XML string to DOM, parse it using this plugin or follow this tutorial
Convert the XML to JSON using this plugin.
jQuery cannot parse XML. If you pass a string full of XML content into the $ function it will typically try to parse it as HTML instead using standard innerHTML. If you really need to parse a string full of XML you will need browser-specific and not-globally-supported methods like new DOMParser and the XMLDOM ActiveXObject, or a plugin that wraps them.
But you almost never need to do this, since an XMLHttpRequest should return a fully-parsed XML DOM in the responseXML property. If your web service is correctly setting a Content-Type response header to tell the browser that what's coming back is XML, then the data argument to your callback function should be an XML Document object and not a string. In that case you should be able to use your example with find() and text() without problems.
If the server-side does not return an XML Content-Type header and you're unable to fix that, you can pass the option type: 'xml' in the ajax settings as an override.

how to handle special characters in strings in a web service?

To show this fundamental issue in .NET and the reason for this question, I have written a simple test web service with one method (EditString), and a consumer console app that calls it.
They are both standard web service/console applications created via File/New Project, etc., so I won't list the whole code - just the methods in question:
Web method:
[WebMethod]
public string EditString(string s, bool useSpecial)
{
return s + (useSpecial ? ((char)19).ToString() : "");
}
[You can see it simply returns the string s if useSpecial is false. If useSpecial is true, it returns s + char 19.]
Console app:
TestService.Service1 service = new SCTestConsumer.TestService.Service1();
string response1 = service.EditString("hello", false);
Console.WriteLine(response1);
string response2 = service.EditString("hello", true); // fails!
Console.WriteLine(response2);
[The second response fails, because the method returns hello + a special character (ascii code 19 for argument's sake).]
The error is:
There is an error in XML document (1, 287)
Inner exception: "'', hexadecimal value 0x13, is an invalid character. Line 1, position 287."
A few points worth mentioning:
The web method itself WORKS FINE when browsing directly to the ASMX file (e.g. http://localhost:2065/service1.asmx), and running the method through this (with the same parameters as in the console application) - i.e. displays XML with the string hello + char 19.
Checking the serialized XML in other ways shows the special character is being encoded properly (the SERVER SIDE seems to be ok which is GOOD)
So it seems the CLIENT SIDE has the issue - i.e. the .NET generated proxy class code doesn't handle special characters
This is part of a bigger project where objects are passed in and out of the web methods - that contain string attributes - these are what need to work properly. i.e. we're de/serializing classes.
Any suggestions for a workaround and how to implement it?
Or have I completely missed something really obvious!!?
PS. I've not had much luck with getting it to use CDATA tags (does .NET support these out of the box?).
You will need to use byte[] instead of strings.
I am thinking of some options that may help you. You can take the route using html entities instead of char(19). or as you said you may want to use CDATA.
To come up with a clean solution, you may not want to put the whole thing in CDATA. I am not sure why you think it may not be supported in .NET. Are you saying this in the context of serialization?

Resources