有没有办法在对象的 JSON 表示中动态切换模型中的字段?

Is there a way to dynamically switch fields from a model in the JSON representation of an object?

我有一个对象的 JSON 表示以及下面列出的相关模型 classes。这两个 classes MinionSettingsLeeSettings 是从基础抽象泛型 class.

派生的 classes
{
    "charSetting": {
        "minionSettings": {
            "key": "minionSettings",
            "value": [1,2,3]
        },
        "leeSettings": {
            "key": "leeSettings",
            "value": [
                {
                    "baseAD": 1,
                    "baseAP": 1,
                    "visible": true
                }
            ]
        }
    }
}
public class CharacterSettingsWrapper
{
    public CharacterSettings CharSetting { get; set; }
}

public class CharacterSettings 
{
    public MinionSettings MinionSettings { get; set; }

    public LeeSettings LeeSettings { get; set; }
}

[DataContract]
public class MinionSettings : CharacterSetting<List<int>>
{
    public MinionSettings()
    {
        Key = "minionSettings";
        Value = new List<int>();
    }
}

public class LeeSettings : CharacterSetting<List<LeeSetting>>
{
    public LeeSettings()
    {
        Key = "leeSettings";
        Value = new List<LeeSetting>();
    }
}

有什么方法可以保留 CharacterSettings class 中的所有字段,但将它们从对象的 JSON 表示中删除,同时保留相关的 key/value对,所以我希望 JSON 如下所示。如果没有,我还能做些什么来实现这一目标?

我试过使用我的基本抽象 class 但由于它是抽象的,我无法创建它的实例所以它不能正常工作,并且该数据是从 JSON 然后放入基于派生的 classes 的相关对象(如两个 classes MinionSettingsLeeSettings

{
   "charSetting":[
      {
         "key":"minionSettings",
         "value":[
            1,
            12,
            3
         ]
      },
      {
         "key":"leeSettings",
         "value":[
            {
               "baseAD":1,
               "baseAP":1,
               "visible":true
            }
         ]
      }
   ]
}

您可以完全使用 JObjectJArray 对象来解决此问题,而无需创建和使用任何域对象。

在下面的代码中我假设节点存在(为了保持代码简单)但是在生产代码中请更喜欢 TryGetValue (Ref) over the index operator (Ref).

//Retrieve the nodes from the original json
var json = File.ReadAllText("sample.json");
var root = JObject.Parse(json);
var charSetting = root["charSetting"];
var minionSettings = charSetting["minionSettings"];
var leeSettings = charSetting["leeSettings"];

//Construct the new json based on the retrieved values
var newcharSetting = new JArray();
newcharSetting.Add(minionSettings);
newcharSetting.Add(leeSettings);
var newRoot = new JObject();
newRoot.Add("charSetting", newcharSetting);
Console.WriteLine(newRoot.ToString());

我还必须提到这段代码严重依赖示例 json 的结构。因此,它不够通用,无法处理与此类似的任何类型的结构。

打印输出如下所示:

{
  "charSetting": [
    {
      "key": "minionSettings",
      "value": [
        1,
        2,
        3
      ]
    },
    {
      "key": "leeSettings",
      "value": [
        {
          "baseAD": 1,
          "baseAP": 1,
          "visible": true
        }
      ]
    }
  ]
}