日期:2014-05-17  浏览次数:20450 次

C#将json转化为对象
本帖最后由 ZZtiWater 于 2013-11-12 15:13:06 编辑
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);