Json.NET
Code Coverage Statistics for Source File

Newtonsoft.Json\Converters\StringEnumConverter.cs

Symbol Coverage: 82.61% (19 of 23)

Branch Coverage: 88.89% (16 of 18)

Cyclomatic Complexity Avg: 3.25 Max:6

Code Lines: 27


L V Source
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
 9
      if (value == null)
47
      {
48
 0
        writer.WriteNull();
49
 0
        return;
50
      }
51

  
52
 9
      Enum e = (Enum) value;
53
 9
      string enumName = e.ToString("G");
54

  
55
 9
      if (char.IsNumber(enumName[0]) || enumName[0] == '-')
56
 4
        writer.WriteValue(value);
57
      else
58
 5
        writer.WriteValue(enumName);
59
 9
    }
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
 11
      Type t = (ReflectionUtils.IsNullableType(objectType))
72
 11
        ? Nullable.GetUnderlyingType(objectType)
73
 11
        : objectType;
74

  
75
 11
      if (reader.TokenType == JsonToken.Null)
76
      {
77
 2
        if (!ReflectionUtils.IsNullableType(objectType))
78
 0
          throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
79

  
80
 2
        return null;
81
      }
82

  
83
 9
      if (reader.TokenType == JsonToken.String)
84
 5
        return Enum.Parse(t, reader.Value.ToString(), true);
85
      
86
 4
      if (reader.TokenType == JsonToken.Integer)
87
 4
        return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t);
88
      
89
 0
      throw new Exception("Unexpected token when parsing enum. Expected String or Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
90
 11
    }
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
 28
      Type t = (ReflectionUtils.IsNullableType(objectType))
102
 28
        ? Nullable.GetUnderlyingType(objectType)
103
 28
        : objectType;
104

  
105
 28
      return t.IsEnum;
106
 28
    }
107
  }
108
}