如何反序列化字符串转换成一个类? [英] How to deserialize a string into a class?

查看:296
本文介绍了如何反序列化字符串转换成一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下文字:

id=1
familyName=Rooney
givenName=Wayne
middleNames=Mark
dateOfBirth=1985-10-24
dateOfDeath=
placeOfBirth=Liverpool
height=1.76
twitterId=@WayneRooney

行用\\ n分离,对用=

Lines are separated by "\n" and pairs are separated by "=".

我有类似标识,FamilyName,给定名称等。

I have a Person class with properties like Id, FamilyName, GivenName, etc.

有没有简单的方法来反序列化上面的文字变成一个Person对象,后来序列化Person对象以正确的线和一对隔板上面的文字?

Is there any easy way to deserialize the above text into a Person object and later serializing a Person object to the above text with the correct line and pair separators?

我希望有可能会像TextSerializer?

I hoped there could be something like a TextSerializer?

基本上,我需要从文件中读取文本例如person1.txt然后将其反序列化为Person对象。

Basically, I'd need to read a text from a file e.g. person1.txt then deserialize it into a Person object.

我想避免手动硬编码为每个属性如果可能的话。
谢谢,

I'd like to avoid hardcoding it manually for each property if possible. Thanks,

推荐答案

反思可以帮助在这里,没有硬编码的属性格式的名称和使用第三方库

Reflection can help here, without hardcoding the propery names and using third party libraries

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

这篇关于如何反序列化字符串转换成一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆