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!

1
  • 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 stackoverflow.com/a/11162133/713981 Commented Feb 26, 2016 at 15:19

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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"});`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.