Vitor Durante
Vitor Durante

Reputation: 1063

Dynamic object in C# to JSON

I am working with C# and I need to create some JSONs for my application. The structure varies and I am not interested in creating a new class to do so. I'm used to work with javascript objects and ruby dictionaries. I found some suggestions online but none of them worked.

At the moment, I am working with a JSON object like:

unit: "country",
suggestions: [
    { "value": "United Arab Emirates", "data": "AE" },
    { "value": "United Kingdom",       "data": "UK" },
    { "value": "United States",        "data": "US" }
]

I would like to know if it is possible to create a object where I could easily add and remove objects from suggestions and also manipulate the object like javascript or ruby.

Thanks!

Upvotes: 0

Views: 183

Answers (2)

ManojAnavatti
ManojAnavatti

Reputation: 644

I would like to know if it is possible to create a object where I could easily add and remove objects

Well, i don't understand your requirement completely. Are you looking for a dictionary?

var dict = new Dictionary<string, object>();
dict.Add("1",new {PropertyA="A",PropertyB="B"});
dict.Add("2", new {SomeotherProp="S"});`

Upvotes: 0

Anderson Pimentel
Anderson Pimentel

Reputation: 5757

Take a look at Json.NET library. You can deserialize your JSON into dynamic objects:

string json = @"[
  {
    'Title': 'Json.NET is awesome!',
    'Author': {
      'Name': 'James Newton-King',
      'Twitter': '@JamesNK',
      'Picture': '/jamesnk.png'
    },
    'Date': '2013-01-23T19:30:00',
    'BodyHtml': '&lt;h3&gt;Title!&lt;/h3&gt;\r\n&lt;p&gt;Content!&lt;/p&gt;'
  }
]";

dynamic blogPosts = JArray.Parse(json);
dynamic blogPost = blogPosts[0];
string title = blogPost.Title;
Console.WriteLine(title);
// Json.NET is awesome!

string author = blogPost.Author.Name;

Console.WriteLine(author);
// James Newton-King

DateTime postDate = blogPost.Date;

Console.WriteLine(postDate);
// 23/01/2013 7:30:00 p.m.

Source: http://www.newtonsoft.com/json/help/html/QueryJsonDynamic.htm

Upvotes: 2

Related Questions