Dynamic class with DeserializeObject delivers error: Unable to find a default constructor to use for type

时间:2019-01-07 12:59:46

标签: c# class dynamic-class-loaders

I am struggling to push my string JSON data in a Dynamic generated class, which now delivers an error which I cannot define on how to solve this

My DynamicClass

public class DynamicClass : DynamicObject
{
    private Dictionary<string, KeyValuePair<Type, object>> _fields;
    public DynamicClass(List<Field> fields)
    {
        _fields = new Dictionary<string, KeyValuePair<Type, object>>();
        fields.ForEach(x => _fields.Add(x.FieldName,
            new KeyValuePair<Type, object>(x.FieldType, null)));
    }
    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (_fields.ContainsKey(binder.Name))
        {
            var type = _fields[binder.Name].Key;
            if (value.GetType() == type)
            {
                _fields[binder.Name] = new KeyValuePair<Type, object>(type, value);
                return true;
            }
            else throw new Exception("Value " + value + " is not of type " + type.Name);
        }
        return false;
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = _fields[binder.Name].Value;
        return true;
    }
}

    private static List<Field> GenerateFields(List<SQL.Column> eColumns)
    {
        var Fields = new List<Field>();
        foreach (SQL.Column col in eColumns)
        {
            try
            {
                var DataTypes = GetDataTypes();
                var DataType = DataTypes.Where(x => x.Id == Convert.ToInt64(col.DataType)).First();
                switch (DataType.Id)
                {
                    case 1:
                    case 6:
                        {
                            Fields.Add(new Field(col.Name, typeof(string)));
                            break;
                        }
                    case 2:
                        {
                            Fields.Add(new Field(col.Name, typeof(DateTime)));
                            break;
                        }
                    case 3:
                        {
                            Fields.Add(new Field(col.Name, typeof(Guid)));
                            break;
                        }
                    case 4:
                        {
                            Fields.Add(new Field(col.Name, typeof(long)));
                            break;
                        }
                    case 5:
                        {
                            Fields.Add(new Field(col.Name, typeof(decimal)));
                            break;
                        }
                    case 7:
                        {
                            Fields.Add(new Field(col.Name, typeof(float)));
                            break;
                        }
                    case 8:
                        {
                            Fields.Add(new Field(col.Name, typeof(byte[])));
                            break;
                        }
                    case 9:
                        {
                            Fields.Add(new Field(col.Name, typeof(double)));
                            break;
                        }
                    case 10:
                        {
                            Fields.Add(new Field(col.Name, typeof(object)));
                            break;
                        }
                    case 11:
                        {
                            Fields.Add(new Field(col.Name, typeof(char)));
                            break;
                        }
                    case 12:
                        {
                            Fields.Add(new Field(col.Name, typeof(int)));
                            break;
                        }
                    default:
                        Fields.Add(new Field(col.Name, typeof(object)));
                        break;
                }
            }
            catch (Exception e)
            {
                #region Error
                ledger._base.Errors.Add(new Error
                {
                    Message = "Something went wrong in connect Ledger to SuperNode, ledger will be unable to establish connection to system",
                    Sys_Message = e.Message,
                    Process = "ledger.data._base.GetSqlData",
                    Line = 38,
                    Priority = 1
                });
                #endregion
            }
        }
        return Fields;
    }

Sample data: [{"Id":"1","Name":"Test product 001","Description":"wehfwouhf","Quantity":"12","Price":"25","Child":""},{"Id":"2","Name":"name of the product","Description":"Explain the product","Price":8.34,"Quantity":1,"Child":null},{"Id":"3","Name":"name of the product 002","Description":"Explain the product","Price":8.34,"Quantity":1,"Child":null}]

DynamicClass dynamicClass = new DynamicClass(GenerateFields(eColumns));
var vReturn = JsonConvert.DeserializeObject<List<DynamicClass>>(retV);

This last call it delivers the error "Unable to find a default constructor to use for type ledger.data.DynamicClass. Path '[0].Id', line 1, position 7."

_fields = Count = 6

Class being generated

{[Id, [System.String, ]]},{[Name, [System.String, ]]},{[Description, [System.String, ]]},{[Quantity, [System.String, ]]} ,{[Price, [System.String, ]]},{[Child, [System.String, ]]}

Class being used

public class Field
{
    public Field(string name, Type type)
    {
        this.FieldName = name;
        this.FieldType = type;
    }
    public string FieldName;
    public Type FieldType;
}

I have noticed that the return from the dynamic generated class misses the object (Dictionary>) however I assume that this should be the actually JSON value.

Can somebody shine a light on this, why I get this error?

1 个答案:

答案 0 :(得分:0)

如果对象为空值(例如x字符串= null或任何对象),则您显然会收到此错误。 解决方案实际上非常简单...浪费了2个完美的工作日... https://stackify.com/nullreferenceexception-object-reference-not-set/