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

偶尔善良 提交于 2019-12-07 09:19:49

问题


I have the code like this:

var json = GetJsonData(path);
JObject event_dates_data = JObject.Parse(json);
var event_dates_list = JObject.Parse(event_dates_data["document"]["date"].ToString());
var event_dates = JsonConvert.DeserializeObject<List<EventDate>>(event_dates_list.ToString());

Json may contains an array objects (for example "date:[{},{},{}]") or only one (for example "date:{}")

Json looks like that:

{
"document": {
"result": "success",
"resultcode": "000000",
"note": null,
"totaldates": "1",
"date": {
  "date_id": "351314",
  "live": "n",
  "datestart": "2012-03-07",
  "dateend": "2015-03-07",
  "timestart": "12:00",
  "timeend": "14:00",
  "date_available": "10000"
}
}
}

Or:

{
"document": {
"result": "success",
"resultcode": "000000",
"note": null,
"totaldates": "4",
"date": [
  {
    "date_id": "346022",
    "live": "n",
    "datestart": "2011-02-19",
    "dateend": "2011-02-19",
    "timestart": "12:00",
    "timeend": "14:00",
    "date_available": "10000"
  },
  {
    "date_id": "346023",
    "live": "n",
    "datestart": "2011-02-20",
    "dateend": "2011-02-20",
    "timestart": "12:00",
    "timeend": "14:00",
    "date_available": "10000"
  },
  {
    "date_id": "346024",
    "live": "n",
    "datestart": "2011-02-21",
    "dateend": "2011-02-21",
    "timestart": "12:00",
    "timeend": "14:00",
    "date_available": "10000"
  },
  {
    "date_id": "546580",
    "live": "y",
    "datestart": "2015-08-15",
    "dateend": "2015-08-15",
    "timestart": "12:00",
    "timeend": "14:00",
    "date_available": "10000"
  }
]
}
}

I have the poco for the "date":

public class EventDate {

    [JsonProperty("date_id")]
    public string Id { get; set; }


    [JsonProperty("live")]
    [JsonConverter(typeof(AvailableForSalesFiledConverter))]
    public bool AvailableForSales { get; set; }


    [JsonProperty("datestart")]
    public string DateStart { get; set; }


    [JsonProperty("dateend")]
    public string DateEnd { get; set; }


    [JsonProperty("timestart")]
    public string TimeStart { get; set; }


    [JsonProperty("timeend")]
    public string TimeEnd { get; set; }


    [JsonProperty("date_available")]
    public int DateAvailable { get; set; }
}

So when I'm trying to deserialize I getting exception: "Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[TicketProvider.BrownPaperTickets.Entities.EventDate]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'date_id', line 2, position 13." How can I get it to List?


回答1:


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());



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/25580680/deserialize-from-json-where-can-be-single-t-object-or-array-of-t-into-listt

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