Error when deserializing JSON to Object

前端 未结 7 2111
别跟我提以往
别跟我提以往 2020-12-18 04:29

I need to convert JSON data that I get from a REST API and convert them to CSV for some analytic. The problem is that the JSON data do not necessarily follow the same conten

7条回答
  •  一向
    一向 (楼主)
    2020-12-18 04:48

    Since you're trying to deserialize an object type into a list type, it won't deseralize directly.

    You can do this:

    var data = JsonConvert.DeserializeObject(jsonData);
    var rows = new List();
    
    foreach (dynamic item in data)
    {
        var newData = new DeserializedData();
        foreach (dynamic prop in item)
        {
             var row = new KeyValuePair
             (prop.Name.ToString(), prop.Value.ToString());
             newData.Add(row);
        }
        rows.Add(newData);
    }
    

    Here are new classes

    //class for key value type data
    
    class DeserializedData
    {
        List> NewData = 
        new List>();
    
        internal void Add(KeyValuePair row)
        {
            NewData.Add(row);
        }
    }
    
    
    [DataContract]
    class ObjectDataList
    {
        [DataMember(Name ="data")]
        List Data { get; set; }
        public IEnumerator GetEnumerator()
        {
            foreach (var d in Data)
            {
                yield return d;
            }
        }
    }
    
        

    提交回复
    热议问题