在JSON反序列化之后,在对象和动态创建的对象之间进行映射

时间:2017-10-28 11:58:08

标签: c# json object dynamic mapping

如果我不知道动态对象的字段,我如何在实例化一个类创建的对象和由JSON反序列化(JsonConvert)创建的动态对象之间进行映射?换句话说,我想更新按名称匹配的动态对象字段。

这是我的示例代码:

string json = {\"NDG\":7803, \"NumberOfNights\":2, \"Nome\":\"Ago\", \"Cognome\":\"Mar\", \"CognomeNome\":\"\"};
string djson = ?? //I don't know the structure coming from a call as parameter but I know there are some json string identical fields  

public class myVars
{
    public string Userid { get; set; }
    public string Nome { get; set; }
    public string Cognome { get; set; }
    public string CognomeNome { get; set; }
}

myVars object1 = JsonConvert.DeserializeObject<myVars>(json);
dynamic object2 = JObject.Parse(djson); // object2 contains a field named "CognomeNome"


myVars.CognomeNome = myVars.Cognome + myVarsNome;
MapObjects(object1 , object2);
string rjson = JsonConvert.SerializeObject(object2); //returns {"CognomeNome":""}

public static object MapObjects(object source, object target)
    {
        foreach (PropertyInfo sourceProp in source.GetType().GetProperties())
        {
            PropertyInfo targetProp = target.GetType().GetProperties().Where(p => p.Name == sourceProp.Name).FirstOrDefault();
            if (targetProp != null && targetProp.GetType().Name == sourceProp.GetType().Name)
            {
                targetProp.SetValue(target, sourceProp.GetValue(source));
            }
        }
        return target;
    }

1 个答案:

答案 0 :(得分:1)

最简单的方法是使用现有的一个自动化程序(Alternatives to AutoMapper

例如,这个: https://github.com/agileobjects/AgileMapper/wiki/Performing-Updates听起来就像你要求的那样。