欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现的json序列化和反序列化代码实例

程序员文章站 2023-11-06 21:18:58
using system; using system.collections.generic; using system.web.script.serializ...
using system;
using system.collections.generic;
using system.web.script.serialization;
using system.configuration;
using system.runtime.serialization.json;
using system.runtime.serialization;
using system.io;
using system.text;


namespace webapplication1
{

  //方法一:引入system.web.script.serialization命名空间使用 javascriptserializer类实现简单的序列化
  [serializable]
  public class person
  {
    
    private int id;
    /// <summary>
    /// id
    /// </summary>
    public int id
    {
      get { return id; }
      set { id = value; }
    }

    private string name;
    /// <summary>
    /// 姓名
    /// </summary>
    public string name
    {
      get { return name; }
      set { name = value; }
    }
  }

  //方法二:引入 system.runtime.serialization.json命名空间使用 datacontractjsonserializer类实现序列化
  //可以使用ignoredatamember:指定该成员不是数据协定的一部分且没有进行序列化,datamember:定义序列化属性参数,使用datamember属性标记字段必须使用datacontract标记类 否则datamember标记不起作用。
  [datacontract]
  public class person1
  {
    
    [ignoredatamember]
    public int id { get; set; }

    [datamember(name = "name")]
    public string name { get; set; }
    [datamember(name = "sex")]
    public string sex { get; set; }

  }

  public partial class _default : system.web.ui.page
  {
    string constr = configurationmanager.connectionstrings["connstr"].connectionstring;
    
    protected void page_load(object sender, eventargs e)
    {
      
      person p1 = new person();
      p1.id = 1;
      p1.name = "dxw";
      person p2 = new person();
      p2.id = 2;
      p2.name = "wn";

      list<person> listperson = new list<person>();
      listperson.add(p1);
      listperson.add(p2);

      javascriptserializer js = new javascriptserializer();
      //json序列化
      string s = js.serialize(listperson);
      response.write(s);



      //方法二
      person1 p11 = new person1();
      p11.id = 1;
      p11.name = "hello";
      p11.sex = "男";
      datacontractjsonserializer json = new datacontractjsonserializer(p11.gettype());

      string szjson = "";

      //序列化

      using (memorystream stream = new memorystream())

      {

        json.writeobject(stream, p11);

        szjson = encoding.utf8.getstring(stream.toarray());

        response.write(szjson);
      }

      //反序列化

      //using (memorystream ms = new memorystream(encoding.utf8.getbytes(szjson)))

      //{

      //  datacontractjsonserializer serializer = new datacontractjsonserializer(typeof(people));

      //  person1 _people = (person1)serializer.readobject(ms);

      //}
     }
    


    protected void button1_click(object sender, eventargs e)
    {
      response.write(constr);
    }


  }