我有以下文字:
id=1
familyName=Rooney
givenName=Wayne
middleNames=Mark
dateOfBirth=1985-10-24
dateOfDeath=
placeOfBirth=Liverpool
height=1.76
twitterId=@WayneRooney
行由" \ n"分隔和对由" ="。
分隔我有一个Person类,其中包含Id,FamilyName,GivenName等属性。
有没有简单的方法将上述文本反序列化为Person对象,然后使用正确的行和对分隔符将Person对象序列化为上述文本?
我希望有类似TextSerializer的东西吗?
基本上,我需要从文件中读取文字,例如person1.txt然后将其反序列化为Person对象。
我希望尽可能避免为每个属性手动编码。 谢谢,
答案 0 :(得分:1)
反射可以在这里提供帮助,无需硬编码属性名称和使用第三方库
var person = Deserialize<Person2>("a.txt");
T Deserialize<T>(string fileName)
{
Type type = typeof(T);
var obj = Activator.CreateInstance(type);
foreach (var line in File.ReadLines(fileName))
{
var keyVal = line.Split('=');
if (keyVal.Length != 2) continue;
var prop = type.GetProperty(keyVal[0].Trim());
if (prop != null)
{
prop.SetValue(obj, Convert.ChangeType(keyVal[1], prop.PropertyType));
}
}
return (T)obj;
}
public class Person2
{
public int id { set; get; }
public string familyName { set; get; }
public string givenName { set; get; }
public string middleNames { set; get; }
public string dateOfBirth { set; get; }
public string dateOfDeath { set; get; }
public string placeOfBirth { set; get; }
public double height { set; get; }
public string twitterId { set; get; }
}
答案 1 :(得分:1)
这也是一种可行的解决方案。 如果可能,您可以尝试在创建时将文本格式化为json。 所以你不需要所有这些治疗。只需使用Json.net
即可public class Person
{
public int id { set; get; }
public string familyName { set; get; }
public string givenName { set; get; }
public string middleNames { set; get; }
public string dateOfBirth { set; get; }
public string dateOfDeath { set; get; }
public string placeOfBirth { set; get; }
public double height { set; get; }
public string twitterId { set; get; }
}
class Program
{
static void Main(string[] args)
{
string line;
string newText = "{";
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while ((line = file.ReadLine()) != null)
{
newText += line.Insert(line.IndexOf("=") + 1, "\"") + "\",";
}
file.Close();
newText = newText.Remove(newText.Length -1);
newText = newText.Replace("=", ":");
newText += "}";
Person Person = JsonConvert.DeserializeObject<Person>(newText);
Console.ReadLine();
}
}
希望得到这个帮助。
答案 2 :(得分:0)
正如其他人所说,你有几种选择:
通过阅读文件(以下示例)手动执行此操作
类人物 { public int ID {get;组; } public string FamilyName {get;组; }
public Person(string file)
{
if (!File.Exists(file))
return;
string[] personData = File.ReadAllLines(file);
foreach (var item in personData)
{
string[] itemPair = item.Split('='); //do some error checking here to see if = isn't appearing twice
string itemKey = itemPair[0];
string itemValue = itemPair[1];
switch (itemKey)
{
case "familyName":
this.FamilyName = itemValue;
break;
case "id":
this.ID = int.Parse(itemValue);
break;
default:
break;
}
}
}
}