English 中文(简体)
Parsing JSON with JSON.NET
原标题:

I have a JSON string:

 {"responseData": 
     {"results": [
         {"GsearchResultClass": "GblogSearch",
          "title":"u003cbu003eParis Hiltonu003c/bu003e shops at Sydney Michelle boutique in the Beverly Glen u003cbu003e...u003c/bu003e",
           "titleNoFormatting":"Paris Hilton shops at Sydney Michelle boutique in the Beverly Glen ...",
           "postUrl":"http://www.celebrity-gossip.net/celebrities/hollywood/paris-hilton-sydney-michelle-stockup-215844/",
           "content":"u003cbu003eParis Hiltonu003c/bu003e shops at Sydney Michelle boutique in the Beverly Glen Mall - u003cbu003eParis Hiltonu003c/bu003e: Sydney Michelle Stockup.",
           "author":"The Gossip Girls at (c) gossipgirls.com",
           "blogUrl":"http://www.celebrity-gossip.net/",
           "publishedDate":"Tue, 23 Feb 2010 22:26:00 -0800"
         },
         {"GsearchResultClass":"GblogSearch",
          "title":"u003cbu003eParis Hiltonu003c/bu003e having wardrobe woes as she met with her lawyer",
          "titleNoFormatting":"Paris Hilton having wardrobe woes as she met with her lawyer",
          "postUrl":"http://www.celebrity-gossip.net/celebrities/hollywood/paris-hiltons-wardrobe-woes-215855/",
          "content":"u003cbu003eParis Hiltonu003c/bu003e having wardrobe woes as  she met with her lawyer - u003cbu003eParis Hilton su003c/bu003e Wardrobe Woes.",
          "author":"The Gossip Girls at (c) gossipgirls.com","blogUrl":"http://www.celebrity-gossip.net/",
          "publishedDate":"Wed, 24 Feb 2010 11:07:56 -0800"
         },
         {"GsearchResultClass":"GblogSearch",
          "title":"HOT GALLERY: u003cbu003eParis Hiltonu003c/bu003e Turns Her Frown Upside Down | OK u003cbu003e...u003c/bu003e",
          "titleNoFormatting":"HOT GALLERY: Paris Hilton Turns Her Frown Upside Down | OK ...",
          "postUrl":"http://www.okmagazine.com/2010/02/hot-gallery-paris-hilton-turns-her-frown-upside-down/",
          "content":"u003cbu003eParis Hiltonu003c/bu003e kept her game face on yesterday as she headed to a meeting in Hollywood. The socialite maintained her composure, but eventually cracked a smile, 201002.",
          "author":"Brittany Talarico",
          "blogUrl":"http://www.okmagazine.com/",
          "publishedDate":"Wed, 24 Feb 2010 07:57:10 -0800"
         },
         {"GsearchResultClass":"GblogSearch",
          "title":"Love It Or Hate It: u003cbu003eParis Hiltonu003c/bu003e | ImNotObsessed.com",
          "titleNoFormatting":"Love It Or Hate It: Paris Hilton | ImNotObsessed.com",
          "postUrl":"http://www.imnotobsessed.com/2010/02/24/love-it-or-hate-it-paris-hilton",
          "content":"tweetmeme_url u003d "http://www.imnotobsessed.com/2010/02/24/love-it-or-hate-it-u003cbu003eparisu003c/bu003e-u003cbu003ehiltonu003c/bu003e";tweetmeme_element_id u003d  #tweetmeme-widget-139430e62dc37d7a2aa71840d6444572 ;That s some dress u003cbu003eParis Hiltonu003c/bu003e was seen wearing while shopping in ...",
          "author":"Vera",
          "blogUrl":"http://www.imnotobsessed.com/",
          "publishedDate":"Wed, 24 Feb 2010 10:44:28 -0800"
         }],
    "cursor": { 
        "pages": [
            {"start":"0","label":1},
            {"start":"4","label":2},
            {"start":"8","label":3},
            {"start":"12","label":4},
            {"start":"16","label":5},
            {"start":"20","label":6},
            {"start":"24","label":7},
            {"start":"28","label":8}],
        "estimatedResultCount":"8035445",
        "currentPageIndex":0,
        "moreResultsUrl":"http://blogsearch.google.com/blogsearch?oeu003dutf8u0026ieu003dutf8u0026safeu003dactiveu0026sourceu003dudsu0026startu003d0u0026hlu003denu0026qu003dParis+Hilton"
        }
     }, 
"responseDetails": null, 
"responseStatus": 200}

ed. note: line breaks added for readability

and I m using Json.NET to parse it, however its giving me a null

this is my code:

JObject o = JObject.Parse(json); // <- where json is the string above

string name = (string)o["responseData"];

BUT its giving me this error :

Can not convert {null} to String.
最佳回答

Have you tried things like?

string gsearchresultclass= (string)o["responseData"]["results"][0]["GsearchResultClass"];
string title= (string)o["responseData"]["results"][0]["title"];
string titlenoformat= (string)o["responseData"]["results"][0]["titleNoFormatting"];
string url = (string)o["responseData"]["results"][0]["postUrl"];
string content = (string)o["responseData"]["results"][0]["content"];
string author = (string)o["responseData"]["results"][0]["author"];
string blogurl = (string)o["responseData"]["results"][0]["blogUrl"];
string date = (string)o["responseData"]["results"][0]["publishedDate"];

What exactly are you trying to get into the name variable?

问题回答

Using Json.Net, you can deserialize the object like this:

BlogSearch search = JsonConvert.DeserializeObject<BlogSearch>(content);

You would define the BlogSearch object like this:

[JsonObject(MemberSerialization.OptIn)]
public class BlogSearch
{
    [JsonProperty(PropertyName = "responseData")]
    public BlogSearchResponse SearchResponse { get; set; }
}

You keep defining objects until you have all the ones you are interested in.

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx
Its a good alternative to your method, that I would recommend...
Hope that helps...

If you re posting your JSON object raw to the Web API then you will run into this problem. The Deserializer is expecting an actual string and not an object or an array. Because it is using a JsonMediaTypeFormatter, it won t know how to translate what is being passed to it.

You need to do the following to avoid the null:

public HttpResponseMessage postBlogSearch([FromBody] JToken json){
    var jsonResult = JObject.Parse(json.ToString());
    var name = jsonResult["responseData"].ToString();
}

For more information see this article.





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签