[英]Unable Deserialize the JSON List into List of Objects in C#
I am currently working on a solution that Deserializes the list of email from json
array, Once I get the list of email objects, I am validating using another class then set into another list.
下面是反序列化的代碼:
static void Main(string[] args)
{
string jsonTest = "{\"Emails\":[\"testUser@gmail.com\",\"testUser2@gmail.com\"]}";
Class1 contact = JsonConvert.DeserializeObject<Class1>(jsonTest);
Console.WriteLine(contact.Emails[0]);
Console.WriteLine(contact.Emails[1]);
}
而且,下面是用於反序列化的Class1
的 class 定義:
public class Class1
{
private readonly List<ValidateEmail> emailsobj;
public List<string> Emails
{
get
{
return emailsobj.Select(o => o.EmailAdd).ToList();
}
set
{
foreach (string email in value)
{
emailsobj.Add(new ValidateEmail(email));
}
}
}
}
並且,下面是validate
class:
public class ValidateEmail
{
public string EmailAdd { get; set; }
private bool Valid;
public ValidateEmail(string value)
{
try
{
MailAddress mail = new MailAddress(EmailAdd);
EmailAdd = value;
Valid = true;
}
catch (FormatException)
{
Valid = false;
}
}
}
每當我反序列化時,我都會在線收到異常:
Console.WriteLine(contact.Emails[0]);
Newtonsoft.Json.JsonSerializationException:從“JsonGenerator.Class1”上的“電子郵件”獲取值時出錯。 ---> System.ArgumentNullException:值不能是 null。 (參數“來源”)
看起來List<Email>
從未設置。 對此有任何幫助,將不勝感激。
如果您使用 Lists - ObjectCreationHandling
,則必須設置以下設置(替換)。
Replace
總是創建新對象並為Lists
啟用 setter 屬性!
因此,在Class1
中初始化新列表后,如下所示:
private readonly List<ValidateEmail> emailsobj = new List<ValidateEmail>();
更改代碼以進行設置:
var settings = new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace
};
Class1 contact = JsonConvert.DeserializeObject<Class1>(jsonTest, settings);
看這里的詳細解釋!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.