DeserializeObject错误:值不能为空

本文关键字:不能 错误 DeserializeObject | 更新日期: 2023-09-27 18:12:07

我在xamarin中使用插件Newtonsoft.Json。窗体应用程序,用于序列化和反序列化类型为Form的对象

public class Form
{
    [JsonProperty("id")]
    public int id { set; get; }
    [JsonProperty("title")]
    public string title { set; get; }
    [JsonProperty("body")]
    public string body { set; get; }
    [JsonProperty("department_id")]
    public string department_id { set; get; }
    [JsonProperty("fields")]
    public List<FormField> fields { set; get; }
}
public class FormField
{
    [JsonProperty("id")]
    public int id { set; get; }
    [JsonProperty("title")]
    public string label { set; get; }
    [JsonProperty("inputtype")]
    public string inputtype { set; get; }
    [JsonProperty("key")]
    public string key { set; get; }
    [JsonProperty("item_order")]
    public int order { set; get; }
    [JsonProperty("required")]
    public bool isRequired { set; get; }
    [JsonProperty("enabled")]
    public bool isEnabled { set; get; }
    public CellCustom fieldObject { set; get;}

    public FormField()
    {
        fieldObject = CreateInstance() as CellCustom;
    }
    private object CreateInstance()
    {
        return Activator.CreateInstance(Type.GetType("Hura.Models.Cells." + inputtype));
    }
    public Cell createCell()
    {
        return fieldObject.createCell();
    }
}

这里是反序列化代码

string str= @"{""id"": 17,""title"": ""testform"",""body"": ""null"",""department_id"": 5,""fields"": [{""id"": 28,""title"": ""null"",""inputtype"": ""text"",""key"": ""f1474532070512"",""item_order"": 1,""required"": true,""enabled"": true}]}";
Form tstfrm = JsonConvert.DeserializeObject<Form>(str);
MainPage = new FillForm(tstfrm); 

但是当我运行这段代码时,它给了我错误System.ArgumentNullException: Value cannot be null. Parameter name: type,即使我在JSON对象中没有任何名为"类型"的字段!

我的代码中的问题是什么,我如何解决它?

DeserializeObject错误:值不能为空

您需要确保类型"Hura.Models.Cells." + inputtype存在于当前执行的程序集或mscorlib.dll中。如果没有,则必须指定程序集名称。(参见这里)。

在您的示例代码中,请求的类型名称是Hura.Models.Cells.text,它不存在,因此向Activator.CreateInstance的类型参数返回null。

也许一个空支票就足够了,但这取决于你想如何处理这种情况

相关文章: