c# - 如何将 JSON 对象与当前类合并
问题描述
我正在尝试创建一个可以自动从 json 文件保存和加载自己的成员的类。
我想知道的是 NewtonSoft.Json 是否已经提供了一种方法来做到这一点,或者我是否必须使用反射。
class Settings
{
// this is my setting
public bool dostuff = false;
public int maxstuff = 123;
public string namestuff = "foo";
List<string> arrayofstuff = new List<string>();
private string fileLocation;
public Settings(string fileLocation)
{
this.fileLocation = fileLocation;
}
public void LoadSettings()
{
string content = System.IO.File.ReadAllText(this.fileLocation);
JObject data = JObject.Parse(content);
// Normally I would have a sub class that contains all the settings
// I would create an instance of it. Serialize into a JObject
// Then merge with the data object.
// Then use ToObject to assign the updated values
myDuplicateJObject.Merge(data, new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Union
});
// However I need to apply it to the current object which is "this"
}
public void SaveSettings()
{
System.IO.File.WriteAllText(this.fileLocation, JsonConvert.SerializeObject(this));
}
}
我目前能想到的解决这个问题的唯一两种方法是使用反射来尝试合并我的类的重复副本,或者创建一个包含所有设置的子类并将其用作成员。
解决方案
你可以使用 JsonConvert.PopulateObject,传入this
它。
public class Settings
{
public string Name = "foo";
public void Populate(string json)
{
JsonConvert.PopulateObject(json, this);
}
}
您可以更改 Populate 方法以读取 JSON 文件本身。
推荐阅读
- javascript - 在其中一个页面中未检测到 Jquery + asp.net
- html - 如何摆脱具有必需属性的 HTML 表单
- javascript - 使用 React hooks (useRef) 将类组件转换为功能组件——如何避免“未定义”错误
- python - 重命名文件以包含基于前一个工作日的后缀
- database - 池中的理想连接数是多少?
- c# - 我可以拥有一个具有多个阅读器的 C# System.IO.Pipelines.Pipe 吗?
- c - pthread_attr_setschedparam() 返回非零但 errno = 成功 ...(Linux、C、Ubuntu 18.04.4)
- vba - 当 DocVariable 字段包含在 TextBox 中时,如何使用 VBA 用字符串值填充 DocVariable
- postgresql - 将包含列表的记录值与 Postgres 中的列值进行比较
- java - Java、Apache POI、XSSFWorkbook 极慢