是否可以使json.net跳过序列化字典中的某些默认值

时间:2019-01-30 11:45:45

标签: c# dictionary uwp json.net

我想跳过一些与默认值相同的字典值。

这是该词典的简化代码

public Dictionary<int, Item> allItems;

public class Item
{
    public bool IsSelected;
    public List<string> SelectionInfo;
}

因此,截至目前,我的JSON输出如下所示:

"allItems": {
    "0": {
      "IsSelected": true,
      "SelectionInfo": [
        "yes",
        "maybe",
        "no"
      ]
    },
    "1": {
      "IsSelected": false,
      "SelectionInfo": []
    }
  }

我想跳过“ 1”,但不要完全跳过它,至少要保留密钥,以便以后可以恢复。并在字典上有0和1

喜欢吗?

"allItems": {
    "0": {
      "IsSelected": true,
      "SelectionInfo": [
        "yes",
        "maybe",
        "no"
      ]
    },
    "1": { }
  }

我环顾四周,发现可以使用JsonConverter。但是我的案例JSON工具在另一个项目(Utility.Please.TurnToJson(item);)上,我想保持一致,并且在所有项目中仅使用一个JSON。也许如果JsonConverter是唯一的选择,至少可以向我提供有关如何将自定义JsonConverter传递到该项目的解决方案。

///somewhat like this?
Utility.Please.TurnToJson(item, new List<object>(){
    typeof(Custom1),
    typeof(Custom2)
});

1 个答案:

答案 0 :(得分:0)

这是可以为您提供预期输出的JsonConverter。

如果IsSelected = falseSelectionInfo数组为空,转换器可以保留您的密钥。

public class MyCustomJsonConverter : JsonConverter
{
    public override bool CanRead
    {
        get { return false; }
    }

    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JObject jObj = new JObject();
        if (value != null)
        {
            var dict = JObject.Parse(value as string)["allItems"].ToObject<Dictionary<string, Item>>();
            foreach (var item in dict)
            {
                JObject jObject = new JObject();

                if (item.Value.IsSelected == false && item.Value.SelectionInfo.Count == 0)
                {
                    jObj.Add(new JProperty(item.Key, new JObject()));
                }
                else
                {
                    jObj.Add(new JProperty(item.Key, JObject.FromObject(item.Value)));
                }
            }
        }

        JObject jMainObject = new JObject();
        jMainObject.Add(new JProperty("allItems", jObj));
        jMainObject.WriteTo(writer);
    }
}

用法:

string json = File.ReadAllText(@"Path to your json file");

string output = JsonConvert.SerializeObject(json, new MyCustomJsonConverter());

输出:

enter image description here