~ubuntu-branches/ubuntu/trusty/smuxi/trusty-proposed

« back to all changes in this revision

Viewing changes to lib/Newtonsoft.Json/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs

  • Committer: Package Import Robot
  • Author(s): Mirco Bauer
  • Date: 2013-05-25 22:11:31 UTC
  • mfrom: (1.2.12)
  • Revision ID: package-import@ubuntu.com-20130525221131-nd2mc0kzubuwyx20
Tags: 0.8.11-1
* [22d13d5] Imported Upstream version 0.8.11
* [6d2b95a] Refreshed patches
* [89eb66e] Added ServiceStack libraries to smuxi-engine package
* [848ab10] Enable Campfire engine
* [c6dbdc7] Always build db4o for predictable build result
* [13ec489] Exclude OS X specific libraries from dh_clideps

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#region License
2
 
// Copyright (c) 2007 James Newton-King
3
 
//
4
 
// Permission is hereby granted, free of charge, to any person
5
 
// obtaining a copy of this software and associated documentation
6
 
// files (the "Software"), to deal in the Software without
7
 
// restriction, including without limitation the rights to use,
8
 
// copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 
// copies of the Software, and to permit persons to whom the
10
 
// Software is furnished to do so, subject to the following
11
 
// conditions:
12
 
//
13
 
// The above copyright notice and this permission notice shall be
14
 
// included in all copies or substantial portions of the Software.
15
 
//
16
 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
 
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
 
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
 
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
 
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
 
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
 
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
 
// OTHER DEALINGS IN THE SOFTWARE.
24
 
#endregion
25
 
 
26
 
using System;
27
 
using System.Globalization;
28
 
using Newtonsoft.Json.Utilities;
29
 
 
30
 
namespace Newtonsoft.Json.Converters
31
 
{
32
 
  /// <summary>
33
 
  /// Converts an <see cref="Enum"/> to and from its name string value.
34
 
  /// </summary>
35
 
  public class StringEnumConverter : JsonConverter
36
 
  {
37
 
 
38
 
    /// <summary>
39
 
    /// Writes the JSON representation of the object.
40
 
    /// </summary>
41
 
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
42
 
    /// <param name="value">The value.</param>
43
 
    /// <param name="serializer">The calling serializer.</param>
44
 
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
45
 
    {
46
 
      if (value == null)
47
 
      {
48
 
        writer.WriteNull();
49
 
        return;
50
 
      }
51
 
 
52
 
      Enum e = (Enum) value;
53
 
      string enumName = e.ToString("G");
54
 
 
55
 
      if (char.IsNumber(enumName[0]) || enumName[0] == '-')
56
 
        writer.WriteValue(value);
57
 
      else
58
 
        writer.WriteValue(enumName);
59
 
    }
60
 
 
61
 
    /// <summary>
62
 
    /// Reads the JSON representation of the object.
63
 
    /// </summary>
64
 
    /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
65
 
    /// <param name="objectType">Type of the object.</param>
66
 
    /// <param name="existingValue">The existing value of object being read.</param>
67
 
    /// <param name="serializer">The calling serializer.</param>
68
 
    /// <returns>The object value.</returns>
69
 
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
70
 
    {
71
 
      Type t = (ReflectionUtils.IsNullableType(objectType))
72
 
        ? Nullable.GetUnderlyingType(objectType)
73
 
        : objectType;
74
 
 
75
 
      if (reader.TokenType == JsonToken.Null)
76
 
      {
77
 
        if (!ReflectionUtils.IsNullableType(objectType))
78
 
          throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
79
 
 
80
 
        return null;
81
 
      }
82
 
 
83
 
      if (reader.TokenType == JsonToken.String)
84
 
        return Enum.Parse(t, reader.Value.ToString(), true);
85
 
      
86
 
      if (reader.TokenType == JsonToken.Integer)
87
 
        return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t);
88
 
      
89
 
      throw new Exception("Unexpected token when parsing enum. Expected String or Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
90
 
    }
91
 
 
92
 
    /// <summary>
93
 
    /// Determines whether this instance can convert the specified object type.
94
 
    /// </summary>
95
 
    /// <param name="objectType">Type of the object.</param>
96
 
    /// <returns>
97
 
    ///         <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
98
 
    /// </returns>
99
 
    public override bool CanConvert(Type objectType)
100
 
    {
101
 
      Type t = (ReflectionUtils.IsNullableType(objectType))
102
 
        ? Nullable.GetUnderlyingType(objectType)
103
 
        : objectType;
104
 
 
105
 
      return t.IsEnum;
106
 
    }
107
 
  }
 
1
#region License
 
2
// Copyright (c) 2007 James Newton-King
 
3
//
 
4
// Permission is hereby granted, free of charge, to any person
 
5
// obtaining a copy of this software and associated documentation
 
6
// files (the "Software"), to deal in the Software without
 
7
// restriction, including without limitation the rights to use,
 
8
// copy, modify, merge, publish, distribute, sublicense, and/or sell
 
9
// copies of the Software, and to permit persons to whom the
 
10
// Software is furnished to do so, subject to the following
 
11
// conditions:
 
12
//
 
13
// The above copyright notice and this permission notice shall be
 
14
// included in all copies or substantial portions of the Software.
 
15
//
 
16
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 
17
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 
18
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 
19
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 
20
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 
21
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 
22
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 
23
// OTHER DEALINGS IN THE SOFTWARE.
 
24
#endregion
 
25
 
 
26
using System;
 
27
using System.Collections.Generic;
 
28
using System.Globalization;
 
29
using System.Reflection;
 
30
using System.Runtime.Serialization;
 
31
using Newtonsoft.Json.Utilities;
 
32
#if NET20
 
33
using Newtonsoft.Json.Utilities.LinqBridge;
 
34
#else
 
35
using System.Linq;
 
36
#endif
 
37
 
 
38
namespace Newtonsoft.Json.Converters
 
39
{
 
40
  /// <summary>
 
41
  /// Converts an <see cref="Enum"/> to and from its name string value.
 
42
  /// </summary>
 
43
  public class StringEnumConverter : JsonConverter
 
44
  {
 
45
    private readonly Dictionary<Type, BidirectionalDictionary<string, string>> _enumMemberNamesPerType = new Dictionary<Type, BidirectionalDictionary<string, string>>();
 
46
 
 
47
    /// <summary>
 
48
    /// Gets or sets a value indicating whether the written enum text should be camel case.
 
49
    /// </summary>
 
50
    /// <value><c>true</c> if the written enum text will be camel case; otherwise, <c>false</c>.</value>
 
51
    public bool CamelCaseText { get; set; }
 
52
    
 
53
    /// <summary>
 
54
    /// Writes the JSON representation of the object.
 
55
    /// </summary>
 
56
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
 
57
    /// <param name="value">The value.</param>
 
58
    /// <param name="serializer">The calling serializer.</param>
 
59
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
 
60
    {
 
61
      if (value == null)
 
62
      {
 
63
        writer.WriteNull();
 
64
        return;
 
65
      }
 
66
 
 
67
      Enum e = (Enum)value;
 
68
 
 
69
      string enumName = e.ToString("G");
 
70
 
 
71
      if (char.IsNumber(enumName[0]) || enumName[0] == '-')
 
72
      {
 
73
        writer.WriteValue(value);
 
74
      }
 
75
      else
 
76
      {
 
77
        BidirectionalDictionary<string, string> map = GetEnumNameMap(e.GetType());
 
78
 
 
79
        string resolvedEnumName;
 
80
        map.TryGetByFirst(enumName, out resolvedEnumName);
 
81
        resolvedEnumName = resolvedEnumName ?? enumName;
 
82
 
 
83
        if (CamelCaseText)
 
84
        {
 
85
          string[] names = resolvedEnumName.Split(',').Select(item => StringUtils.ToCamelCase(item.Trim())).ToArray();
 
86
          resolvedEnumName = string.Join(", ", names);
 
87
        }
 
88
 
 
89
        writer.WriteValue(resolvedEnumName);
 
90
      }
 
91
    }
 
92
 
 
93
    /// <summary>
 
94
    /// Reads the JSON representation of the object.
 
95
    /// </summary>
 
96
    /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
 
97
    /// <param name="objectType">Type of the object.</param>
 
98
    /// <param name="existingValue">The existing value of object being read.</param>
 
99
    /// <param name="serializer">The calling serializer.</param>
 
100
    /// <returns>The object value.</returns>
 
101
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 
102
    {
 
103
      Type t = (ReflectionUtils.IsNullableType(objectType))
 
104
      ? Nullable.GetUnderlyingType(objectType)
 
105
      : objectType;
 
106
 
 
107
      if (reader.TokenType == JsonToken.Null)
 
108
      {
 
109
        if (!ReflectionUtils.IsNullableType(objectType))
 
110
          throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
 
111
 
 
112
        return null;
 
113
      }
 
114
 
 
115
      if (reader.TokenType == JsonToken.String)
 
116
      {
 
117
        var map = GetEnumNameMap(t);
 
118
        string resolvedEnumName;
 
119
        map.TryGetBySecond(reader.Value.ToString(), out resolvedEnumName);
 
120
        resolvedEnumName = resolvedEnumName ?? reader.Value.ToString();
 
121
 
 
122
        return Enum.Parse(t, resolvedEnumName, true);
 
123
      }
 
124
 
 
125
      if (reader.TokenType == JsonToken.Integer)
 
126
        return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t);
 
127
 
 
128
      throw JsonSerializationException.Create(reader, "Unexpected token when parsing enum. Expected String or Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
 
129
    }
 
130
 
 
131
    /// <summary>
 
132
    /// A cached representation of the Enum string representation to respect per Enum field name.
 
133
    /// </summary>
 
134
    /// <param name="t">The type of the Enum.</param>
 
135
    /// <returns>A map of enum field name to either the field name, or the configured enum member name (<see cref="EnumMemberAttribute"/>).</returns>
 
136
    private BidirectionalDictionary<string, string> GetEnumNameMap(Type t)
 
137
    {
 
138
      BidirectionalDictionary<string, string> map;
 
139
 
 
140
      if (!_enumMemberNamesPerType.TryGetValue(t, out map))
 
141
      {
 
142
        lock (_enumMemberNamesPerType)
 
143
        {
 
144
          if (_enumMemberNamesPerType.TryGetValue(t, out map))
 
145
            return map;
 
146
 
 
147
          map = new BidirectionalDictionary<string, string>(
 
148
            StringComparer.OrdinalIgnoreCase,
 
149
            StringComparer.OrdinalIgnoreCase);
 
150
 
 
151
          foreach (FieldInfo f in t.GetFields())
 
152
          {
 
153
            string n1 = f.Name;
 
154
            string n2;
 
155
            
 
156
#if !NET20
 
157
            n2 = f.GetCustomAttributes(typeof (EnumMemberAttribute), true)
 
158
                          .Cast<EnumMemberAttribute>()
 
159
                          .Select(a => a.Value)
 
160
                          .SingleOrDefault() ?? f.Name;
 
161
#else
 
162
            n2 = f.Name;
 
163
#endif
 
164
 
 
165
            string s;
 
166
            if (map.TryGetBySecond(n2, out s))
 
167
            {
 
168
              throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'."
 
169
                .FormatWith(CultureInfo.InvariantCulture, n2, t.Name));
 
170
            }
 
171
 
 
172
            map.Add(n1, n2);
 
173
          }
 
174
 
 
175
          _enumMemberNamesPerType[t] = map;
 
176
        }
 
177
      }
 
178
 
 
179
      return map;
 
180
    }
 
181
 
 
182
    /// <summary>
 
183
    /// Determines whether this instance can convert the specified object type.
 
184
    /// </summary>
 
185
    /// <param name="objectType">Type of the object.</param>
 
186
    /// <returns>
 
187
    /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
 
188
    /// </returns>
 
189
    public override bool CanConvert(Type objectType)
 
190
    {
 
191
      Type t = (ReflectionUtils.IsNullableType(objectType))
 
192
      ? Nullable.GetUnderlyingType(objectType)
 
193
      : objectType;
 
194
 
 
195
      return t.IsEnum();
 
196
    }
 
197
  }
108
198
}
 
 
b'\\ No newline at end of file'