Json.NET
Code Coverage Statistics for Source File

Newtonsoft.Json\Converters\BsonObjectIdConverter.cs

Symbol Coverage: 84.62% (11 of 13)

Branch Coverage: 71.43% (5 of 7)

Cyclomatic Complexity Avg: 1.50 Max:2

Code Lines: 13


L V Source
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using Newtonsoft.Json.Bson;
6
using System.Globalization;
7
using Newtonsoft.Json.Utilities;
8

  
9
namespace Newtonsoft.Json.Converters
10
{
11
  /// <summary>
12
  /// Converts a <see cref="BsonObjectId"/> to and from JSON and BSON.
13
  /// </summary>
14
  public class BsonObjectIdConverter : JsonConverter
15
  {
16
    /// <summary>
17
    /// Writes the JSON representation of the object.
18
    /// </summary>
19
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
20
    /// <param name="value">The value.</param>
21
    /// <param name="serializer">The calling serializer.</param>
22
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
23
    {
24
 1
      BsonObjectId objectId = (BsonObjectId) value;
25

  
26
 1
      BsonWriter bsonWriter = writer as BsonWriter;
27
 1
      if (bsonWriter != null)
28
      {
29
 1
        bsonWriter.WriteObjectId(objectId.Value);
30
      }
31
      else
32
      {
33
 0
        writer.WriteValue(objectId.Value);
34
      }
35
 1
    }
36

  
37
    /// <summary>
38
    /// Reads the JSON representation of the object.
39
    /// </summary>
40
    /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
41
    /// <param name="objectType">Type of the object.</param>
42
    /// <param name="existingValue">The existing value of object being read.</param>
43
    /// <param name="serializer">The calling serializer.</param>
44
    /// <returns>The object value.</returns>
45
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
46
    {
47
 1
      if (reader.TokenType != JsonToken.Bytes)
48
 0
        throw new JsonSerializationException("Expected Bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
49

  
50
 1
      byte[] value = (byte[])reader.Value;
51

  
52
 1
      return new BsonObjectId(value);
53
 1
    }
54

  
55
    /// <summary>
56
    /// Determines whether this instance can convert the specified object type.
57
    /// </summary>
58
    /// <param name="objectType">Type of the object.</param>
59
    /// <returns>
60
    /// 	<c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
61
    /// </returns>
62
    public override bool CanConvert(Type objectType)
63
    {
64
 292
      return (objectType == typeof (BsonObjectId));
65
 292
    }
66
  }
67
}