C#将json转化为对象解决方法
C#将json转化为对象
错误:
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
------解决方案--------------------
是1个列表,而不是1个对象。
------解决方案--------------------
你这明显是一个集合;
public class TempContacts
{
public string DisplayName { get; set; }
public string Email { get; set; }
}
string jsonContacts="[{\"DisplayName\":\"name1\",\"Email\":\"email1\"},{\"DisplayName\":\"name2\",\"Email\":\"email2\"}]";
Models.TempContacts contacts = JsonConvert.DeserializeObject<Models.TempContacts>(jsonContacts);
错误:
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
C#
解析
json
------解决方案--------------------
是1个列表,而不是1个对象。
class Program
{
static void Main(string[] args)
{
string jsonContacts = "[{\"DisplayName\":\"name1\",\"Email\":\"email1\"},{\"DisplayName\":\"name2\",\"Email\":\"email2\"}]";
List<TempContacts> list = JsonConvert.DeserializeObject<List<TempContacts>>(jsonContacts);
}
}
public class Data
{
public List<TempContacts> list { get; set; }
}
public class TempContacts
{
public string DisplayName { get; set; }
public string Email { get; set; }
}
------解决方案--------------------
你这明显是一个集合;
string jsonContacts="[{\"DisplayName\":\"name1\",\"Email\":\"email1\"},{\"DisplayName\":\"name2\",\"Email\":\"email2\"}]";
IList<Models.TempContacts> contactsList = JsonConvert.DeserializeObject<Models.TempContacts>(jsonContacts);