[英]how can I parse object into a class like json deserialize?
I want to make a own parser that can parse object values into the <T>
Type that contains class with propertys.我想制作一个自己的解析器,可以将对象值解析为包含具有属性的类的
<T>
类型。
the class ASObject
is just a Dictionary<string, object>
类
ASObject
只是一个Dictionary<string, object>
public class Example {
public string User { get; set; }
public int Id { get; set; }
}
public static class ServiceResultParser<T>
{
public static T Parse(ASObject AS)
{
foreach(var l in AS.Values)
{
}
}
}
Usage:
var Result = ServiceResultParser.Parse<Example>(theobject);
string User = Result.User;
that is only a test class that I called Example
in json we can use JsonConvert.DeserializeObject<T>(value)
这只是一个我在 json 中称为
Example
的测试类,我们可以使用JsonConvert.DeserializeObject<T>(value)
and no I dont want parse json.不,我不想解析 json。
how can I now parse the value into the Example
class?我现在如何将值解析为
Example
类?
regarding.关于。
You could check wheter T has a property with a name that matches the Dictionary's key:您可以检查 T 是否具有名称与字典键匹配的属性:
public static class ServiceResultParser<T> where T : new()
{
public static T Parse(ASObject AS)
{
var temp = GetObject();
foreach(var l in AS)
{
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (PropertyInfo property in properties)
{
if(property.Name == l.Key) property.SetValue(temp, l.Value);
}
}
return temp;
}
protected T GetObject()
{
return new T();
}
}
You should also check if the properties type match, etc...您还应该检查属性类型是否匹配等...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.