Ernie
Ernie

Reputation: 567

Creating nested objects from JSON

I have the following JSON that needs to be represented as an object.

[
    {
        "to": "+27001234567",
        "scheduling":{
            "date": DateTime,
            "description": String
        },
        "id": "Hello World!"
    }
]

The problem I'm having is with the object inside of the object. What would be the way to do this?

Upvotes: 0

Views: 115

Answers (2)

Musa Hafalir
Musa Hafalir

Reputation: 1770

You can represent nested objects from json to c# like this:

public class Scheduling
{
    public DateTime date { get; set; }
    public string description { get; set; }
}

public class RootObject
{
    public string to { get; set; }
    public Scheduling scheduling { get; set; }
    public string id { get; set; }
}

Also I want you to check the site that I found so useful: http://json2csharp.com/

Upvotes: 1

Richard
Richard

Reputation: 22016

If you are parsing JSON in a C# object, then you can either use dynamic types or you can parse to an actual object using libraries such as JSON.net found here:

http://james.newtonking.com/json

such as this:

    string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;

Upvotes: 1

Related Questions