• json序列化以及反序列化存在多个对象时候的处理


    存在多个对象的时候,只需要将反序列化存在的对象,遍历出来即可。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    using System.IO;

    namespace json
    {
    //学生类
    [DataContract]
    public class Student
    {
    [DataMember]
    public int ID { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public int Age { get; set; }

    [DataMember]
    public string Sex { get; set; }

    public Person person { get; set; }

    public Student() {
    ID = 101;
    Name="gogo";
    Age = 25;
    Sex = "男";
    person = new Person();
    }
    }

    //person类
    [DataContract]
    public class Person
    {
    [DataMember]
    public string person_name { get; set; }
    [DataMember]
    public int Age { get; set; }

    public Person (string name,int age){
    person_name=name;
    Age=age;
    }
    public Person(){
    person_name = "yuanshifu";
    Age=10;
    }
    }

    //封装两个类
    public class Animal
    {

    public Student student0 { get; set; }

    public List<Person> personList{get;set;}

    public Animal(Student stu, List<Person> perlist)
    {
    student0 = stu;
    personList = perlist;
    }

    public Animal(){ }
    }
    //测试
    public class test {
    static void Main(){
    //准备序列化的数据
    List<Person> pl=new List<Person>();
    Person p1=new Person("fu1",10);
    Person p2=new Person("fu2",20);

    pl.Add(p1);
    pl.Add(p2);
    Student stu10=new Student();
    Animal ani = new Animal(stu10,pl);
    //开始序列化
    DataContractJsonSerializer dj=new DataContractJsonSerializer(typeof(Animal));
    MemoryStream ms=new MemoryStream();
    dj.WriteObject(ms,ani);
    ms.Position = 0;
    StreamReader sr=new StreamReader(ms,Encoding.UTF8);
    string str=sr.ReadToEnd();
    Console.WriteLine(str);
    Console.ReadKey();

    //反序列化
    using(MemoryStream ms0=new MemoryStream(Encoding.UTF8.GetBytes(str))){
    Animal animal = (Animal)dj.ReadObject(ms0);//反序列化的具体代码
    Student st1 = animal.student0;

    List<Person> listperson = animal.personList;

    Console.WriteLine("反序列化");
    Console.WriteLine(st1.ID+":"+st1.Name+":"+st1.person+":"+st1.Sex);
    Console.WriteLine("打印集合");
    //遍历集合
    foreach(Person fg in listperson){

    Console.WriteLine(fg.person_name);
    Console.WriteLine(fg.Age);
    }
    Console.ReadKey();
    }
    }
    }
    }

  • 相关阅读:
    C# 打印多页tif
    页面动态加载js文件
    CPrintDialog 构造函数参数详解
    DEVMODE 结构体
    对C#对象的Shallow、Deep Cloning认识【转】
    PowerShell 启动应用程序【转】
    中文网页的字体
    css3自适应布局单位vw,vh你知道多少?
    微信小程序轮播图宽高计算
    更改wordpress的默认登录页面名称wp-login
  • 原文地址:https://www.cnblogs.com/anlegou/p/6490332.html
Copyright © 2020-2023  润新知