0
如何通過實例化一個類創建的對象與由JSON反序列化(JsonConvert)創建的動態對象之間的映射考慮到我不知道動態對象的字段?換句話說,我想更新按名稱匹配的動態對象字段。JSON反序列化後對象與動態創建的對象之間的映射
這是我的示例代碼:
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;
}
你到目前爲止嘗試過什麼? –
您需要爲您的問題添加更多信息才能負責(例如,也許?)。看起來['AutoMapper'支持](https://github.com/AutoMapper/AutoMapper/wiki/Dynamic-and-ExpandoObject-Mapping)for'dynamic',所以這大概延伸到'JObject' – StuartLC
可能的重複[如何從一個靜態對象創建一個動態對象?](https://stackoverflow.com/questions/23156815/c-sharp-how-to-create-a-dynamic-object-from-a-static-object ) – derloopkat