C# 对象和json的互换(2)

1、使用NewtonSoft.Json.dll

 

序列化:

string jsonStr= JavaScriptConvert.SerializeObject(person);//person为实例化之后的对象

 

反序列化:

 


Person person = (Person)JavaScriptConvert.DeserializeObject(jsonStr, typeof(Person));


  

2、使用JavaScriptSerializr进行Json的序列化和反序列化 

序列化: 

 JavaScriptSerializer jss = new JavaScriptSerializer();
string jsonStr= jss.Serialize(person);

反序列化:Person p1=jss.Deserialize(jsonStr);

  

序列化list对象: 

  

 public string Serialize( JavaScriptSerializer serializer)
    {
        List list = new PersonMgr().getPersons();


        JsonArrayCollection jac = new JsonArrayCollection();

        foreach (Person p in list)
        {
            JsonObjectCollection joc = new JsonObjectCollection();
            Dictionary row = new Dictionary();
            foreach (System.Reflection.PropertyInfo pro in p.GetType().GetProperties())
            {
                joc.Add(new JsonStringValue(pro.Name,pro.GetValue(p,null).ToString()));
               
            }
            jac.Add(joc);
        }
     
      
        return jac.ToString();
    }

  

反序列化: 

public List<object> DeSerialize<T>(string jsonStr)
    {

        List<object> list = new List<object>();
        JsonTextParser jtp = new JsonTextParser();
        JsonArrayCollection jac = jtp.Parse(jsonStr) as JsonArrayCollection;
        T o = Activator.CreateInstance<T>();
        foreach (JsonObjectCollection joc in jac)
        {
           
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(joc.ToString())))
            {
               DataContractJsonSerializer serializer = new DataContractJsonSerializer(o.GetType());
               list.Add((T)serializer.ReadObject(ms));
             }
        }
        return list;
    }

 

posted on 2014-10-12 09:33  小风铃  阅读(183)  评论(0)    收藏  举报

导航