英文:
Convert the model's fields as Dictionary in another model's field
问题
{
// other fields
"FirstModelTransfer": {
"firstname": "Sample firstname",
"lastname": "Sample lastname"
}
}
英文:
I have this model:
namespace SomeApp.Models
{
public class FirstModel
{
public int uid { get; set; }
public string? id { get; set; }
public string? firstname { get; set; }
public string? lastname { get; set; }
}
}
whose fields I need to convert to a dictionary or JSON object in another model. I'm using the GetFields
Method.
namespace SomeApp.Models
{
public class SecondModel
{
// other fields
public Dictionary<string, string> FirstModelTransfer { get; set; }
public void SetFirstModelTransfer(FirstModel firstModel)
{
FieldInfo[] firstModelFields = typeof(FirstModel).GetFields();
Dictionary<string, string> dict = new();
foreach (var firstModelField in firstModelFields)
{
string fieldName = firstModelField.Name;
string fieldValue = firstModelField.GetValue(fieldName).ToString();
dict[fieldName] = fieldValue;
}
FirstModelTransfer = dict;
}
}
}
I want the result to look like
{
// other fields
"FirstModelTransfer": {
"firstname": "Sample firstname",
"lastname": "Sample lastname"
}
}
But currently, it looks like this,
{
// other fields
"FirstModelTransfer": {
"additionalProp1": "string",
"additionalProp2": "string",
"additionalProp3": "string"
}
}
I don't know if this matters but:
services.AddDbContext<SecondModelsContext>();
services.AddDbContext<FirsModelsContext>();
This is the ordering of the dbContexts in which each model was registered.
答案1
得分: 1
From your code, you are trying to get the properties but not fields in FirstModel
class.
Thus, you should get the properties as PropertyInfo[]
via GetProperties()
.
PropertyInfo[] firstModelFields = typeof(FirstModel).GetProperties();
To get the property value via Reflection, you have to pass the object instance as mentioned in PropertyInfo.GetValue(Object)
method.
string fieldValue = firstModelField.GetValue(firstModel)?.ToString();
Alternatively, you may use the Newtonsoft.Json library to convert an object into a Dictionary<string, string>
instance without Reflection.
using Newtonsoft.Json.Linq;
dict = JObject.FromObject(firstModel)
.ToObject<Dictionary<string, string>>();
英文:
From your code, you are trying to get the properties but not fields in FirstModel
class.
Thus, you should get the properties as PropertyInfo[]
via GetProperties()
.
PropertyInfo[] firstModelFields = typeof(FirstModel).GetProperties();
To get the property value via Reflection, you have to pass the object instance as mentioned in PropertyInfo.GetValue(Object)
method.
string fieldValue = firstModelField.GetValue(firstModel)?.ToString();
Alternatively, you may use the Newtonsoft.Json library to convert an object into a Dictionary<string, string>
instance without Reflection.
using Newtonsoft.Json.Linq;
dict = JObject.FromObject(firstModel)
.ToObject<Dictionary<string, string>>();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论