在JSON .NET中使用字典键作为引用

时间:2018-09-24 10:34:53

标签: c# json json.net

我需要以这种格式解析一些JSON:

{
    "Sources": {
        "Videos1": {
            "Order": "Default",
            "PathPattern": "Videos/**/*"
        },
        "Images": {
            "Order": "Default",
            "PathPattern": "Images/*.jpg"
        }
    },
    "MasterSource": "Videos1"
}

这应该能够代表一个像这样的类:

public class Playlist
{
    public Dictionary<string, Source> Sources { get; set; }

    public Source MasterSource { get; set; }
    // etc
}

很显然,JSON.NET不知道如何将字符串转换为Source或在需要首先解析的字典中找到它。除了使用string字段,然后在获得Source时查找它们之外,还有什么方法可以使用JSON转换器或其他方法实现?

(注意:JSON中的Sources字典将始终排在第一位)

1 个答案:

答案 0 :(得分:1)

简化的转换器看起来像这样

public class PlayListConverter : JsonConverter<Playlist> {
    public override Playlist ReadJson(JsonReader reader, Type objectType, Playlist existingValue, bool hasExistingValue, JsonSerializer serializer) {
        var json = JObject.ReadFrom(reader);
        var sources = json["Sources"].ToObject<Dictionary<string, Source>>();
        var master = json["MasterSource"].Value<string>();

        var result = new Playlist() {
            Sources = sources,
            MasterSource = sources[master]
        };

        return result;
    }

    public override void WriteJson(JsonWriter writer, Playlist value, JsonSerializer serializer) {
        throw new NotImplementedException();
    }
}

并应用

public class Source {
    public string Order { get; set; }
    public string PathPattern { get; set; }
}

[JsonConverter(typeof(PlayListConverter))]
public class Playlist {
    public Dictionary<string, Source> Sources { get; set; }

    public Source MasterSource { get; set; }

    // etc
}