imin
imin

Reputation: 4578

put parent label for multiple values in json

here's my code:

private class ReturnResponse
{
    public string result, sessionId, eventList;
    public List<string> eventIDs = new List<string>();
    public List<string> eventNames = new List<string>();
}


var obj = new ReturnResponse
          {
              result = "1",
              sessionId = "123213214214",
              eventIDs = getEventsInfo["listEventID"],
              eventNames = getEventsInfo["listEventName"]
          };
var json = new JavaScriptSerializer().Serialize(obj);
Response.Write(json);

the code above will display json like this:

{"result":"1", "sessionId":"123213214214","eventIDs":["1464","1480"],"eventNames":["hari malaysia","kame"]}

but what I need is something like this

{"result":"1", "sessionId":"123213214214","eventList": {"eventIDs":["1464","1480"],"eventNames":["hari malaysia","kame"]}}

as you can see, eventIDs and eventNames are put under 'parent' label, eventList. How can I do that?

Upvotes: 0

Views: 47

Answers (2)

ekad
ekad

Reputation: 14614

You can create another class that contains eventIDs and eventNames property, let's say it's named Event

public class Event
{
    public List<string> eventIDs = new List<string>();
    public List<string> eventNames = new List<string>();
}

then change the type of eventList to Event in ReturnResponse class

public class ReturnResponse
{
    public string result { get; set; }
    public string sessionId { get; set; }
    public Event eventList { get; set; }
}

and initiate obj based on the above change as follows

var obj = new ReturnResponse
          {
              result = "1",
              sessionId = "123213214214",
              eventList = new Event() 
                          {
                              eventIDs = getEventsInfo["listEventID"],
                              eventNames = getEventsInfo["listEventName"]
                          }
          };
var json = new JavaScriptSerializer().Serialize(obj);
Response.Write(json);    

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

Then your classes should look like this:

private class ReturnResponse
    {
        public string result, sessionId;
        public EventList eventList;
    }

public class EventList
{
  public List<string> eventIDs {get;set;}
  public List<string> eventNames {get;set;}
}

and when populating it:

var obj = new ReturnResponse
          {
            result = "1",
            sessionId = "123213214214",
            eventList = new EventList() 
                        {  
                          eventIDs = getEventsInfo["listEventID"],
                          eventNames =  getEventsInfo["listEventName"]
                        }
          }; 

Upvotes: 2

Related Questions