|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using Newtonsoft.Json; |
| 4 | + |
| 5 | +namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters |
| 6 | +{ |
| 7 | + /// <summary> |
| 8 | + /// This is necessary because Newtonsoft.Json creates <see cref="Uri"/> instances with |
| 9 | + /// <see cref="UriKind.RelativeOrAbsolute"/> which treats UNC paths as relative. NuGet.Core uses |
| 10 | + /// <see cref="UriKind.Absolute"/> which treats UNC paths as absolute. For more details, see: |
| 11 | + /// https://github.com/JamesNK/Newtonsoft.Json/issues/2128 |
| 12 | + /// </summary>< |
| 13 | + class DictionaryUriConverter<TKey, TValue> : |
| 14 | + JsonConverter<Dictionary<TKey, TValue>> where TKey : Uri |
| 15 | + { |
| 16 | + private readonly AbsoluteUriConverter _uriConverter = new AbsoluteUriConverter(); |
| 17 | + |
| 18 | + public override Dictionary<TKey, TValue> ReadJson( |
| 19 | + JsonReader reader, |
| 20 | + Type objectType, |
| 21 | + Dictionary<TKey, TValue> existingValue, |
| 22 | + bool hasExistingValue, |
| 23 | + JsonSerializer serializer) |
| 24 | + { |
| 25 | + if (reader.TokenType != JsonToken.StartObject) |
| 26 | + { |
| 27 | + throw new JsonException(); |
| 28 | + } |
| 29 | + |
| 30 | + Dictionary<TKey, TValue> value = new Dictionary<TKey, TValue>(); |
| 31 | + |
| 32 | + while (reader.Read()) |
| 33 | + { |
| 34 | + if (reader.TokenType == JsonToken.EndObject) |
| 35 | + { |
| 36 | + return value; |
| 37 | + } |
| 38 | + |
| 39 | + // Get the key. |
| 40 | + if (reader.TokenType != JsonToken.PropertyName) |
| 41 | + { |
| 42 | + throw new JsonException(); |
| 43 | + } |
| 44 | + |
| 45 | + // Get the stringified Uri. |
| 46 | + string propertyName = (string) reader.Value; |
| 47 | + reader.Read(); |
| 48 | + |
| 49 | + Uri key = new Uri(propertyName, UriKind.Absolute); |
| 50 | + |
| 51 | + // Get the value. |
| 52 | + TValue v = serializer.Deserialize<TValue>(reader); |
| 53 | + |
| 54 | + // Add to dictionary. |
| 55 | + value.Add((TKey) key, v); |
| 56 | + } |
| 57 | + |
| 58 | + throw new JsonException(); |
| 59 | + } |
| 60 | + |
| 61 | + public override void WriteJson( |
| 62 | + JsonWriter writer, |
| 63 | + Dictionary<TKey, TValue> value, |
| 64 | + JsonSerializer serializer) |
| 65 | + { |
| 66 | + writer.WriteStartObject(); |
| 67 | + |
| 68 | + foreach (KeyValuePair<TKey, TValue> kvp in value) |
| 69 | + { |
| 70 | + writer.WritePropertyName(AbsoluteUriConverter.Convert(kvp.Key)); |
| 71 | + serializer.Serialize(writer, kvp.Value); |
| 72 | + } |
| 73 | + |
| 74 | + writer.WriteEndObject(); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments