在C#中从文件流反序列化多个对象

时间:2019-05-10 10:44:35

标签: c# .net json json.net

我无法从FileStream反序列化多个JSON对象;我收到了SerializationException。

我可以用一个对象来做,而不能用多个对象来做。 我正在尝试从.txt文件进行此操作:

csharks imi 1991
csharks romeo 1989
csharks peti 1989
csharks berti 1991
csharks bala 1993

JSON:

  [
   {
     "Name": "imi",
     "TeamName": "csharks"
   },
   {
     "Name": "romeo",
     "TeamName": "csharks"
   },
   {
     "Name": "peti",
     "TeamName": "csharks"
   },
   {
     "Name": "berti",
     "TeamName": "csharks"
   },
   {
     "Name": "bala",
     "TeamName": "csharks"
   }
 ]

C#代码:

public class Program
{
    private static List<TeamMember> teamMembers = new List<TeamMember>();
    private static List<TeamMember> teamMembersDeserialized = new List<TeamMember>();

    public static void Main(string[] args)
    {
        string teamFile = @"C:\Users\Precision\Downloads\Serializacio\csharks.txt";
        string teamFileJson = @"C:\Users\Precision\Downloads\Serializacio\csharksJSON.json";
        string teamFileJson2 = @"C:\Users\Precision\Downloads\Serializacio\csharksJSON2.json";
        using (FileStream fs = new FileStream(teamFile, FileMode.Open, FileAccess.Read))
        {
            using (StreamReader reader = new StreamReader(fs))
            {
                List<string> memberData = new List<string>();
                while (true)
                {
                    string line = reader.ReadLine();
                    if (line == null)
                    {
                        break;
                    }
                    memberData = line.Split(' ').ToList();

                    TeamMember member = new TeamMember(memberData[0], memberData[1], int.Parse(memberData[2]));
                    teamMembers.Add(member);
                }

            }
        }
        using (FileStream fs = new FileStream(teamFileJson, FileMode.OpenOrCreate, FileAccess.Write))
        {
            foreach (TeamMember member in teamMembers)
            {
                Console.WriteLine(member.ToString());
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(member.GetType());
                jsonSerializer.WriteObject(fs, member);


            }
        }

        using (FileStream fs2 = File.OpenRead(teamFileJson2))
        {
            foreach (TeamMember member in teamMembers)
            {
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(member.GetType());
                {
                    TeamMember memberNew = jsonSerializer.ReadObject(fs2) as TeamMember;
                    teamMembersDeserialized.Add(memberNew);
                }                    
            }
        }

        foreach (TeamMember member in teamMembersDeserialized)
        {
            Console.WriteLine(member.ToString());
        }

        Console.ReadKey();
    }
}

1 个答案:

答案 0 :(得分:0)

以下示例解析您的JSON。我正在使用Newtonsoft.Json命名空间。如果您需要其他帮助,请告诉我。

void Main()
{
    var json = @"[
        {
            'Name': 'imi',
            'TeamName': 'csharks'
        },
        {
            'Name': 'romeo',
            'TeamName': 'csharks'
        },
        {
            'Name': 'peti',
            'TeamName': 'csharks'
        },
        {
            'Name': 'berti',
            'TeamName': 'csharks'
        },
        {
            'Name': 'bala',
            'TeamName': 'csharks'
        }]";

    var teams = JsonConvert.DeserializeObject<List<Team>>(json);

    teams.ForEach(x => Console.WriteLine($"Name: {x.Name}, Team: {x.TeamName}"));
}

public class Team
{
    public String Name { get; set; }
    public String TeamName { get; set; }
}

这将提供以下输出:

Name: imi, Team: csharks
Name: romeo, Team: csharks
Name: peti, Team: csharks
Name: berti, Team: csharks
Name: bala, Team: csharks

要从文件读取此JSON,您可以执行以下操作:

var filename = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
    "test.json");

var json = File.ReadAllText(filename);