-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
ObjectDictionaryConverter.cs
60 lines (54 loc) · 2.29 KB
/
ObjectDictionaryConverter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace TehGM.Wolfringo.Messages.Serialization.Internal
{
/// <summary>Json converter converting Json object into dictionary value, and using one of it's properties as the key.</summary>
/// <typeparam name="TKey">Type of the key.</typeparam>
/// <typeparam name="TValue">Type of the value.</typeparam>
public class ObjectDictionaryConverter<TKey, TValue> : JsonConverter
{
private readonly string _keyPropPath;
/// <inheritdoc/>
/// <param name="keyPropertyPath">Path of the property to use as a key.</param>
public ObjectDictionaryConverter(string keyPropertyPath)
{
this._keyPropPath = keyPropertyPath;
}
/// <inheritdoc/>
public ObjectDictionaryConverter()
: this("Key") { }
/// <inheritdoc/>
public override bool CanConvert(Type objectType)
{
return typeof(IEnumerable<KeyValuePair<TKey, TValue>>).IsAssignableFrom(objectType);
}
/// <inheritdoc/>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
IEnumerable<KeyValuePair<TKey, TValue>> collection = (IEnumerable<KeyValuePair<TKey, TValue>>)value;
JArray results = new JArray();
foreach (KeyValuePair<TKey, TValue> pair in collection)
{
JObject item = JObject.FromObject(pair.Value, serializer);
item.Add(this._keyPropPath, JToken.FromObject(pair.Key, serializer));
results.Add(item);
}
results.WriteTo(writer);
}
/// <inheritdoc/>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JArray jsonArray = JArray.Load(reader);
Dictionary<TKey, TValue> results = new Dictionary<TKey, TValue>(jsonArray.Count);
foreach (JToken obj in jsonArray)
{
TKey key = obj.SelectToken(this._keyPropPath).ToObject<TKey>(serializer);
TValue value = obj.ToObject<TValue>(serializer);
results.Add(key, value);
}
return results;
}
}
}