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

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();
            }
          }  
        }     
    }