0

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!

Vitor Durante
  • 950
  • 8
  • 25
  • You can add and remove the objects on an array list as an example but C# does not allow to add methods or attributes on execution time if that is what you mean, see http://stackoverflow.com/a/11162133/713981 – jclozano Feb 26 '16 at 15:19

2 Answers2

2

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': '<h3>Title!</h3>\r\n<p>Content!</p>'
  }
]";

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

Anderson Pimentel
  • 5,086
  • 2
  • 32
  • 54
0

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"});`
ManojAnavatti
  • 604
  • 1
  • 7
  • 18