using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
[JsonProperty(PropertyName = "sub_AssignedToCompanyId@odata.bind")]
[JsonConverter(typeof(PrefixedGuidConverter), "/accounts")]
public Guid AssignedToCompany{ get; set; }
public class PrefixedGuidConverter : JsonConverter
public PrefixedGuidConverter(string prefix)
throw new ArgumentNullException("prefix");
public override bool CanConvert(Type objectType)
return objectType == typeof(Guid) || objectType == typeof(Guid?);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
if (reader.MoveToContentAndAssert().TokenType == JsonToken.Null)
else if (reader.TokenType == JsonToken.String)
var value = ((string)reader.Value).Trim();
if (value.StartsWith(prefix))
return Guid.Parse(value.Substring(prefix.Length, value.Length - prefix.Length));
throw new JsonSerializationException(string.Format("Unexpected JSON token {0}: {1}.", reader.TokenType, reader.Value));
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
serializer.Serialize(writer, prefix + ((Guid)value).ToString("P", serializer.Culture));
public static partial class JsonExtensions
public static JsonReader ReadToContentAndAssert(this JsonReader reader)
return reader.ReadAndAssert().MoveToContentAndAssert();
public static JsonReader MoveToContentAndAssert(this JsonReader reader)
throw new ArgumentNullException();
if (reader.TokenType == JsonToken.None)
while (reader.TokenType == JsonToken.Comment)
public static JsonReader ReadAndAssert(this JsonReader reader)
throw new ArgumentNullException();
throw new JsonReaderException("Unexpected end of JSON stream.");
public static void Test()
var root = JsonConvert.DeserializeObject<RootObject>(json);
Assert.IsTrue(root.AssignedToCompany == Guid.Parse("f52f9dd7-35e5-e711-813b-480fcff40721"));
var json2 = JsonConvert.SerializeObject(root, Formatting.Indented);
Console.WriteLine("Reserialized JSON:");
Console.WriteLine(json2);
Assert.IsTrue(JToken.DeepEquals(JToken.Parse(json), JToken.Parse(json2)));
""sub_AssignedToCompanyId@odata.bind"": ""/accounts(f52f9dd7-35e5-e711-813b-480fcff40721)""
public static void Main()
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");