我无法从文件流中进行多个json对象;我得到一个序列化exception。
我可以用一个对象做到这一点,但不能与多个对象一起做。我正在从.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:UsersPrecisionDownloadsSerializaciocsharks.txt";
string teamFileJson = @"C:UsersPrecisionDownloadsSerializaciocsharksJSON.json";
string teamFileJson2 = @"C:UsersPrecisionDownloadsSerializaciocsharksJSON2.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();
}
}
以下示例解析您的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);