将多个值的父标签放在 JSON 中
本文关键字:JSON 标签 | 更新日期: 2023-09-27 18:30:39
这是我的代码:
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);
上面的代码将显示 JSON,如下所示:
{"result":"1", "sessionId":"123213214214","eventIDs":["1464","1480"],"eventNames":["hari malaysia","kame"]}
但我需要的是这样的东西
{"result":"1", "sessionId":"123213214214","eventList": {"eventIDs":["1464","1480"],"eventNames":["hari malaysia","kame"]}}
如您所见,eventID 和 eventNames 位于"父"标签 eventList 下。我该怎么做?
那么你的类应该看起来像这样:
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;}
}
填充它时:
var obj = new ReturnResponse
{
result = "1",
sessionId = "123213214214",
eventList = new EventList()
{
eventIDs = getEventsInfo["listEventID"],
eventNames = getEventsInfo["listEventName"]
}
};
您可以创建另一个包含 eventIDs
和 eventNames
属性的类,假设它被命名为 Event
public class Event
{
public List<string> eventIDs = new List<string>();
public List<string> eventNames = new List<string>();
}
然后将eventList
类型更改为Event
ReturnResponse
类
public class ReturnResponse
{
public string result { get; set; }
public string sessionId { get; set; }
public Event eventList { get; set; }
}
并根据上述更改启动obj
,如下所示
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);