Error while deserializing JSON for an object

I need to convert the JSON data that I get from the REST API and convert it to CSV for some analytics. The problem is that JSON data does not necessarily correspond to the same content, so I cannot determine the type to match. This has become a problem that takes too much time. I already created some code, but of course it does not work as it throws an exception on this line

var data = JsonConvert.DeserializeObject<List<object>>(jsonData);

Mistake:

Additional information: It is not possible to deserialize the current JSON object (for example, {"name": "value"}) to type 'System.Collections.Generic.List`1 [System.Object]', because the type for deserialization correctly requires a JSON array ( for example, [1,2,3]).

To fix this error, either change the JSON to a JSON array (for example, [1,2,3]), or change the deserialized type to be a regular .NET type (for example, not a primitive type of integer type, but not a collection type, for example array or list) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to a type to force it to deserialize the JSON object.

Path Data Line 2 Position 10

please let me know what I can do to make this happen.

An example of the data will be like this, data fields can change very often, for example, a new field can be added the next day, so I do not have the right to create a .Net class to map data.

{
  "data": [
    {
      "ID": "5367ab140026875f70677ab277501bfa",
      "name": "Happiness Initiatives - Flow of Communication/Process & Efficiency",
      "objCode": "PROJ",
      "percentComplete": 100.0,
      "plannedCompletionDate": "2014-08-22T17:00:00:000-0400",
      "plannedStartDate": "2014-05-05T09:00:00:000-0400",
      "priority": 1,
      "projectedCompletionDate": "2014-12-05T08:10:21:555-0500",
      "status": "CPL"
    },
    {
      "ID": "555f452900c8b845238716dd033cf71b",
      "name": "UX Personalization Think Tank and Product Strategy",
      "objCode": "PROJ",
      "percentComplete": 0.0,
      "plannedCompletionDate": "2015-12-01T09:00:00:000-0500",
      "plannedStartDate": "2015-05-22T09:00:00:000-0400",
      "priority": 1,
      "projectedCompletionDate": "2016-01-04T09:00:00:000-0500",
      "status": "APR"
    },
    {
      "ID": "528b92020051ab208aef09a4740b1fe9",
      "name": "SCL Health System - full Sitecore implementation (Task groups with SOW totals in Planned hours - do not bill time here)",
      "objCode": "PROJ",
      "percentComplete": 100.0,
      "plannedCompletionDate": "2016-04-08T17:00:00:000-0400",
      "plannedStartDate": "2013-11-04T09:00:00:000-0500",
      "priority": 1,
      "projectedCompletionDate": "2013-12-12T22:30:00:000-0500",
      "status": "CPL"
    }
 ]
}



namespace BusinessLogic
{
    public class JsonToCsv
    {

       public string ToCsv(string jsonData, string datasetName)
       {
          var data = JsonConvert.DeserializeObject<List<object>>(jsonData);
          DataTable table = ToDataTable(data); 
          StringBuilder result = new StringBuilder();

            for (int i = 0; i < table.Columns.Count; i++)
            {
                result.Append(table.Columns[i].ColumnName);
                result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
            }

            foreach (DataRow row in table.Rows)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    result.Append(row[i].ToString());
                    result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
                }
            }

            return result.ToString().TrimEnd(new char[] {'\r', '\n'});

        }

        private DataTable ToDataTable<T>( IList<T> data )
            {
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            for (int i = 0 ; i < props.Count ; i++)
                {
                PropertyDescriptor prop = props[i];
                table.Columns.Add(prop.Name, prop.PropertyType);
                }

            object[] values = new object[props.Count];
            foreach (T item in data)
                {
                for (int i = 0 ; i < values.Length ; i++)
                    {
                    values[i] = props[i].GetValue(item);
                    }

                table.Rows.Add(values);
                }

            return table;
            }


        }
}
+4
source share
5 answers

, List<object>, JSON , data, . . Json.Net . , :

class Root
{
    public List<Dictionary<string, object>> Data { get; set;}
}

:

var data = JsonConvert.DeserializeObject<Root>(jsonData).Data;

, JSON. - . , . , :

foreach (var dict in data)
{
    foreach (var kvp in dict)
    {
        Console.WriteLine(kvp.Key + ": " + kvp.Value);
    }
    Console.WriteLine();
}

Fiddle: https://dotnetfiddle.net/6UaKhJ

+3

, :

using System.Web.Script.Serialization;

JavaScriptSerializer jss = new JavaScriptSerializer();
var d=jss.Deserialize<dynamic>(str);
+1

, , dynamic. , , .

, , , , , . .

, dynamic - , , JSON JavaScript. KeyValuePair .

var data = JsonConvert.DeserializeObject<dynamic>(jsonData);
var rows = new List<string>();

// Go through the overall object, and get each item in 
// the array, or property in a single object.
foreach (KeyValuePair<string, object> item in data)
{
    dynamic obj = item.Value;
    var row = "";

    // Perhaps add a check here to see if there are more
    // properties (if it is an item in an array). If not
    // then you are working with a single object, and each
    // item is a property itself.
    foreach (KeyValuePair<string, object> prop in obj)
    {
        // Very dummy way to demo adding to a CSV
        string += prop.Value.ToString() + ",";
    }

    rows.Add(string);
}

, , , .

+1
source

Try using this class instead of Object

public class Datum
{
    public string ID { get; set; }
    public string name { get; set; }
    public string objCode { get; set; }
    public double percentComplete { get; set; }
    public string plannedCompletionDate { get; set; }
    public string plannedStartDate { get; set; }
    public int priority { get; set; }
    public string projectedCompletionDate { get; set; }
    public string status { get; set; }
}

public class RootObject
{
    public List<Datum> data { get; set; }
}

Change to this:

var data = JsonConvert.DeserializeObject<RootObject>(jsonData);
0
source

Since you are trying to deserialize the type of an object into a type of a list, it will not de-serialize directly.

You can do it:

var data = JsonConvert.DeserializeObject<ObjectDataList>(jsonData);
var rows = new List<DeserializedData>();

foreach (dynamic item in data)
{
    var newData = new DeserializedData();
    foreach (dynamic prop in item)
    {
         var row = new KeyValuePair<string, string>
         (prop.Name.ToString(), prop.Value.ToString());
         newData.Add(row);
    }
    rows.Add(newData);
}

Here are the new classes

//class for key value type data

class DeserializedData
{
    List<KeyValuePair<string, string>> NewData = 
    new List<KeyValuePair<string, string>>();

    internal void Add(KeyValuePair<string, string> row)
    {
        NewData.Add(row);
    }
}


[DataContract]
class ObjectDataList
{
    [DataMember(Name ="data")]
    List<object> Data { get; set; }
    public IEnumerator<object> GetEnumerator()
    {
        foreach (var d in Data)
        {
            yield return d;
        }
    }
}
0
source

Source: https://habr.com/ru/post/1620812/


All Articles