Parse Google JSON response in VB.NET

2020-04-28 02:31发布

问题:

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.

回答1:

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.