42

シリアル化に Json.Net を使用しています。私は辞書を持つクラスを持っています:

public class Test
{
    public string X { get; set; }

    public Dictionary<string, string> Y { get; set; }
}

このオブジェクトをシリアル化して、次の JSON を取得できますか

{
    "X" : "value",
    "key1": "value1",
    "key2": "value2"
}

「key1」、「key2」は辞書のキーですか?

4

3 に答える 3

9

JsonConverter派生クラスを実装します。CustomCreationConverterクラスは、カスタム オブジェクトを作成するための基本クラスとして使用する必要があります。

コンバーターのドラフト バージョン (エラー処理は必要に応じて改善できます):

internal class TestObjectConverter : CustomCreationConverter<Test>
{
    #region Overrides of CustomCreationConverter<Test>

    public override Test Create(Type objectType)
    {
        return new Test
            {
                Y = new Dictionary<string, string>()
            };
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteStartObject();

        // Write properties.
        var propertyInfos = value.GetType().GetProperties();
        foreach (var propertyInfo in propertyInfos)
        {
            // Skip the Y property.
            if (propertyInfo.Name == "Y")
                continue;

            writer.WritePropertyName(propertyInfo.Name);
            var propertyValue = propertyInfo.GetValue(value);
            serializer.Serialize(writer, propertyValue);
        }

        // Write dictionary key-value pairs.
        var test = (Test)value;
        foreach (var kvp in test.Y)
        {
            writer.WritePropertyName(kvp.Key);
            serializer.Serialize(writer, kvp.Value);
        }
        writer.WriteEndObject();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jsonObject = JObject.Load(reader);
        var jsonProperties = jsonObject.Properties().ToList();
        var outputObject = Create(objectType);

        // Property name => property info dictionary (for fast lookup).
        var propertyNames = objectType.GetProperties().ToDictionary(pi => pi.Name, pi => pi);
        foreach (var jsonProperty in jsonProperties)
        {
            // If such property exists - use it.
            PropertyInfo targetProperty;
            if (propertyNames.TryGetValue(jsonProperty.Name, out targetProperty))
            {
                var propertyValue = jsonProperty.Value.ToObject(targetProperty.PropertyType);
                targetProperty.SetValue(outputObject, propertyValue, null);
            }
            else
            {
                // Otherwise - use the dictionary.
                outputObject.Y.Add(jsonProperty.Name, jsonProperty.Value.ToObject<string>());
            }
        }

        return outputObject;
    }

    public override bool CanWrite
    {
        get { return true; }
    }

    #endregion
}

クライアントコード:

var test = new Test
    {
        X = "123",
        Y = new Dictionary<string, string>
            {
                { "key1", "value1" },
                { "key2", "value2" },
                { "key3", "value3" },
            }
    };

string json = JsonConvert.SerializeObject(test, Formatting.Indented, new TestObjectConverter());
var deserializedObject = JsonConvert.DeserializeObject<Test>(json);

注意: プロパティ名とディクショナリのキー名が競合する可能性があります。

于 2013-02-15T12:41:18.177 に答える