2 using System.Collections;
3 using System.Collections.Generic;
5 using Newtonsoft.Json.Serialization;
7 namespace Hammock.Extras.Serialization
10 /// Resolves all property names to JSON conventional standard,
11 /// i.e. JSON name "this_is_a_property" will map to the class property ThisIsAProperty.
12 /// Also finds any property names suffixed with "Attribute" and converts them
13 /// into @properties for XML serialization.
15 public class JsonConventionResolver : DefaultContractResolver
17 public class ToStringComparer : IComparer
19 public int Compare(object x, object y)
21 return x.ToString().CompareTo(y.ToString());
25 protected override IList<JsonProperty> CreateProperties(Type type, Newtonsoft.Json.MemberSerialization memberSerialization)
27 var properties = base.CreateProperties(type, memberSerialization);
29 return CreatePropertiesImpl(properties);
32 private static IList<JsonProperty> CreatePropertiesImpl(IList<JsonProperty> properties)
34 foreach (var property in properties)
36 property.PropertyName = PascalCaseToElement(property.PropertyName);
39 // @'s must come first
40 var result = properties;
42 ArrayList.Adapter((IList)result).Sort(new ToStringComparer());
47 private static string PascalCaseToElement(string input)
49 if (string.IsNullOrEmpty(input))
54 var attributeForSerialization = input.EndsWith("Attribute");
55 if(attributeForSerialization)
57 input = input.Substring(0, input.LastIndexOf("Attribute"));
60 var result = new StringBuilder();
61 result.Append(char.ToLowerInvariant(input[0]));
63 for (var i = 1; i < input.Length; i++)
65 if (char.IsLower(input[i]))
67 result.Append(input[i]);
72 result.Append(char.ToLowerInvariant(input[i]));
76 return attributeForSerialization? string.Concat("@", result) : result.ToString();