首页 > 解决方案 > 如何将 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));
    }
}

我目前能想到的解决这个问题的唯一两种方法是使用反射来尝试合并我的类的重复副本,或者创建一个包含所有设置的子类并将其用作成员。

标签: c#jsonserializationreflectionjson.net

解决方案


你可以使用 JsonConvert.PopulateObject,传入this它。

public class Settings
{
    public string Name = "foo";

    public void Populate(string json)
    {
        JsonConvert.PopulateObject(json, this);
    }
}

您可以更改 Populate 方法以读取 JSON 文件本身。


推荐阅读