Deserialize from json where can be single T object or array of T into List<T> [duplicate]

有些话、适合烂在心里 提交于 2019-12-05 12:24:24
var json = GetJsonData(path);
JObject event_dates_data = JObject.Parse(json);
var event_dates_list = JObject.Parse(event_dates_data["document"]["date"].ToString());
event_dates_list = string.Format("[{0}]", event_dates_list.Trim('[', ']'));
var event_dates = JsonConvert.DeserializeObject<List<EventDate>>(event_dates_list.ToString());

I'm a bit puzzled since it seems you're doing a mishmash of things in there.

I would suggest you create a POCO object that represents your data as a class. It should have a list of type DateTime, and one of EventDate, and when you serialize, you simply serialize the entire class as:

var my_poco = // create your object here;
var poco_as_json = Newtonsoft.Json.JsonConvert.SerializeObject(my_poco);

// You then save that to a file (I assume that's what you're doing)

// Get it back will look like: 
var back_from_json = Newtonsoft.Json.JsonConvert
                                    .DeserializeObject<your_poco_class>(json);

// and then simply use the object's lists:
var dates  = back_from_json.event_dates_list; // list of dates
var events = = back_from_json.events;         // list of events? 

Your poco is for the event date only.
You need another poco with variables for the rest:

"document", "result", "resultcode", "note", "totaldates", "date"

It'll probably be called document, totaldates will be an int, and date will be a List<DateEvent>.
That's what you'll serialize and deserialize.

First of all in your class convert the instance of the class in RootObject to the list for example:

class RootObject
{
public List<Class1> Property1 { get; set; }
}

Now you can access the items in that class as list.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!