-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathRootWrapperConverter.cs
More file actions
75 lines (63 loc) · 2.28 KB
/
Copy pathRootWrapperConverter.cs
File metadata and controls
75 lines (63 loc) · 2.28 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
using Newtonsoft.Json;
namespace OpenStack.Serialization
{
/// <summary>
/// Some of the OpenStack API's like to return a wrapper around the real object requested. This will deal with that root level wrapper.
/// <para>Note that it only affects the root, if there are nested objects that also use this converter, it is assumed that they don't have a wrapper.</para>
/// </summary>
/// <exclude />
public class RootWrapperConverter : DefaultJsonConverter
{
private readonly string _name;
/// <summary>
/// Initializes a new instance of the <see cref="RootWrapperConverter"/> class.
/// </summary>
/// <param name="name">The root json property wrapper.</param>
public RootWrapperConverter(string name)
{
_name = name;
}
/// <inheritdoc/>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
bool isRoot = writer.WriteState == WriteState.Start;
if (isRoot)
{
// Wrap
writer.WriteStartObject();
writer.WritePropertyName(_name);
}
// Default serialization
base.WriteJson(writer, value, serializer);
if (isRoot)
{
writer.WriteEndObject();
}
}
/// <inheritdoc/>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
bool isRoot = reader.Depth == 0;
if (isRoot)
{
// Skip to the desired property
while (reader.Read())
{
if (reader.TokenType != JsonToken.PropertyName || reader.Value.ToString() != _name)
continue;
// Advance to the contained value
reader.Read();
break;
}
}
// Default Deserialization
object result = base.ReadJson(reader, objectType, existingValue, serializer);
if (isRoot)
{
while (reader.Read()) { } // Advance to end
}
return result;
}
}
}