开发者

JSON to C# Classes - Unknown property names

开发者 https://www.devze.com 2023-03-10 01:02 出处:网络
let\'s say I have the following JSON payload; { \"pagemap\": { \"metatags\": [ { \"msapplication-task\": \"name\\u003dAbout Tugberk Ugurlu;action-uri\\u003d/about;icon-uri\\u003d/content/App_Icons/ic

let's say I have the following JSON payload;

  {
   "pagemap": {
    "metatags": [
     {
      "msapplication-task": "name\u003dAbout Tugberk Ugurlu;action-uri\u003d/about;icon-uri\u003d/content/App_Icons/icos/about.ico",
      "msapplication-task": "name\u003dContact;action-uri\u003d/contact;icon-uri\u003d/content/App_Icons/icos/contact.ico",
      "msapplication-task": "name\u003dBlog RSS Feed;action-uri\u003dht开发者_运维技巧tp://feeds.feedburner.com/TugberkUgurlu;icon-uri\u003d/content/App_Icons/icos/rss.ico",
      "msapplication-task": "name\u003dTugberk on Twitter;action-uri\u003dhttp://twitter.com/tourismgeek;icon-uri\u003d/content/App_Icons/icos/twitter.ico",
      "msapplication-starturl": "./",
      "application-name": "Tugberk's Blog",
      "msapplication-tooltip": "bla bla bla..."
     }
    ]
   }
  }

The property names under mettags are dynamic. I mean one of them is msapplication-starturl for this request but it might be msapplication-foo for another.

So what would be the best c# classes for this kind of JSON payload?

EDIT

this is the part of JSON format which google search API gives. Also I am using Json.NET. is There any other way than dynamic?


I'd probably just want the MetaTags array to just get pushed into a Dictionary<string,string> or even just List<string> and then write a helper class that parses msapplication-task values into something you want.

Edit: I believe the OP is looking for some help in how his model class would actually be

public class PageMap
{
    public Dictionary<string,string> MetaTags {get;set; }
}

From looking at that json object, it appears that RestSharp should be able to deserialize it into this class.

Calling code would be similar to

var client = new RestClient("somegoogle.com");
var request = new RestRequest("Some/Foo/Bar", Method.GET)
                                 { RequestFormat = DataFormat.Json }; 
request.AddParameter("p1", "quigybo");
client.Execute<PageMan>(request)


You should look at JSON.NET and JObject for building dynamic loosely typed objects. If you decide to use it, you should NuGet to download it.

Example:

var client = new WebClient();
client.Headers.Add("User-Agent", "your user agent here");
var response = client.DownloadString(new Uri("http://www.domain.com/source-page.html"));
JObject jo = JObject.Parse(response);
0

精彩评论

暂无评论...
验证码 换一张
取 消