0

Help me out to retrieve eventID from this json data:

{"events":[{"eventId":1579,"eventName":"NN - Marathon Rotterdam","startDateTime":"2018-04-06 09:00:00","endDateTime":"2018-04-08 16:30:00"}],"autostartEvent":null}

property were set on interfaces

public interface IEventList : IList<IEvent>
{

    DateTime StartDate { get; }

    DateTime EndDate { get; }

    IEvent AutoStartEvent { get; }
}


public interface IEvent
{
    int Id { get; }

    string Name { get; }

    DateTime StartDate { get; }

    DateTime EndDate { get; }

}

that interface was initialize on eventlist class where deserialize object were mapped on events property.

 public class EventList : IEventList
{
    public object  Events { get; set; }

}

 try
        {
             var deserializeData = JsonConvert.DeserializeObject(json);
            return new EventList
                  {
                     Events=deserializeData 
                  };
        }

so i want to retrieve the eventid from events object.

J_Shrestha
  • 37
  • 1
  • 9

2 Answers2

2

Create related classes on bottom;

public class Event
{
    public int eventId { get; set; }
    public string eventName { get; set; }
    public string startDateTime { get; set; }
    public string endDateTime { get; set; }
}

public class RootObject
{
    public List<Event> events { get; set; }
    public object autostartEvent { get; set; }
}

And Deserialize the json like that;

RootObject root = new System.Web.Script.Serialization.JavaScriptSerializer()
                      .Deserialize<RootObject>(jsonText);

int exampleEventId = root.events.FirstOrDefault().eventId;//Example
ahmeticat
  • 1,899
  • 1
  • 13
  • 28
2

The one approach is that,

Directly parse your JSON with JObject provided by newtonsoft and then retrieve your eventId by Querying your JSON,

So this way you don't need to manage the class hierarchy anymore,

string json = "Your json here";

JObject jObject = JObject.Parse(json);

int eventId = (int)jObject["events"][0]["eventId"];

Output: (From Debugger)

enter image description here

Note: You need to install NewtonSoft NuGet package and import using Newtonsoft.Json.Linq; namespace to your program.

er-sho
  • 9,581
  • 2
  • 13
  • 26