22

This is what I have:

using Newtonsoft.Json;

var json = "{\"someProperty\":\"some value\"}";
dynamic deserialized = JsonConvert.DeserializeObject(json);

This works fine:

Assert.That(deserialized.someProperty.ToString(), Is.EqualTo("some value"));

I want this to work (first letter of properties upper-cased) without changing json:

Assert.That(deserialized.SomeProperty.ToString(), Is.EqualTo("some value"));

4 Answers 4

17

I agree with Avner Shahar-Kashtan. You shouldn't be doing this, especially if you have no control over the JSON.

That said, it can be done with the use of a ExpandoObject and a custom ExpandoObjectConverter. JSON.NET already provides a ExpandoObjectConverter so with some little adjustments you have what you want.

Notice the //CHANGED comments inside the code snippet to show you where I changed it.

public class CamelCaseToPascalCaseExpandoObjectConverter : JsonConverter
{
  //CHANGED
  //the ExpandoObjectConverter needs this internal method so we have to copy it
  //from JsonReader.cs
  internal static bool IsPrimitiveToken(JsonToken token) 
  {
      switch (token)
      {
          case JsonToken.Integer:
          case JsonToken.Float:
          case JsonToken.String:
          case JsonToken.Boolean:
          case JsonToken.Null:
          case JsonToken.Undefined:
          case JsonToken.Date:
          case JsonToken.Bytes:
              return true;
          default:
              return false;
      }
  }

/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
  // can write is set to false
}

/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
  return ReadValue(reader);
}

private object ReadValue(JsonReader reader)
{
  while (reader.TokenType == JsonToken.Comment)
  {
    if (!reader.Read())
      throw new Exception("Unexpected end.");
  }

  switch (reader.TokenType)
  {
    case JsonToken.StartObject:
      return ReadObject(reader);
    case JsonToken.StartArray:
      return ReadList(reader);
    default:
      //CHANGED
      //call to static method declared inside this class
      if (IsPrimitiveToken(reader.TokenType))
        return reader.Value;

      //CHANGED
      //Use string.format instead of some util function declared inside JSON.NET
      throw new Exception(string.Format(CultureInfo.InvariantCulture, "Unexpected token when converting ExpandoObject: {0}", reader.TokenType));
  }
}

private object ReadList(JsonReader reader)
{
  IList<object> list = new List<object>();

  while (reader.Read())
  {
    switch (reader.TokenType)
    {
      case JsonToken.Comment:
        break;
      default:
        object v = ReadValue(reader);

        list.Add(v);
        break;
      case JsonToken.EndArray:
        return list;
    }
  }

  throw new Exception("Unexpected end.");
}

private object ReadObject(JsonReader reader)
{
  IDictionary<string, object> expandoObject = new ExpandoObject();

  while (reader.Read())
  {
    switch (reader.TokenType)
    {
      case JsonToken.PropertyName:
        //CHANGED
        //added call to ToPascalCase extension method       
        string propertyName = reader.Value.ToString().ToPascalCase();

        if (!reader.Read())
          throw new Exception("Unexpected end.");

        object v = ReadValue(reader);

        expandoObject[propertyName] = v;
        break;
      case JsonToken.Comment:
        break;
      case JsonToken.EndObject:
        return expandoObject;
    }
  }

  throw new Exception("Unexpected end.");
}

/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
///     <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
  return (objectType == typeof (ExpandoObject));
}

/// <summary>
/// Gets a value indicating whether this <see cref="JsonConverter"/> can write JSON.
/// </summary>
/// <value>
///     <c>true</c> if this <see cref="JsonConverter"/> can write JSON; otherwise, <c>false</c>.
/// </value>
public override bool CanWrite
{
  get { return false; }
}
}

A simple string to Pascal Case converter. Make it smarter if you need to.

public static class StringExtensions
{
    public static string ToPascalCase(this string s)
    {
        if (string.IsNullOrEmpty(s) || !char.IsLower(s[0]))
            return s;

        string str = char.ToUpper(s[0], CultureInfo.InvariantCulture).ToString((IFormatProvider)CultureInfo.InvariantCulture);

        if (s.Length > 1)
            str = str + s.Substring(1);

        return str;
    }
}

Now you can use it like this.

var settings = new JsonSerializerSettings()
                   {
                       ContractResolver = new CamelCasePropertyNamesContractResolver(),
                       Converters = new List<JsonConverter> { new CamelCaseToPascalCaseExpandoObjectConverter() }
                   };

var json = "{\"someProperty\":\"some value\"}";

dynamic deserialized = JsonConvert.DeserializeObject<ExpandoObject>(json, settings);

Console.WriteLine(deserialized.SomeProperty); //some value

var json2 = JsonConvert.SerializeObject(deserialized, Formatting.None, settings);

Console.WriteLine(json == json2); //true

The ContractResolver CamelCasePropertyNamesContractResolver is used when serializing the object back to JSON and makes it Camel case again. This is also provided by JSON.NET. If you don't need this you can omit it.

Sign up to request clarification or add additional context in comments.

4 Comments

Ok, looks like this is the answer! I hoped there would be a better extension point than this though... I'll upvote now and mark as answered when I've tried it out. Thanks!
Excellent code. Although I completely disagree with the comment that "you shouldn't be doing this". If the json is coming from a javascript client, then this convention mismatch will probably occur. Javascript's convention for properties is camelCase. C# convention for properties is Pascal. It's gotta be converted sometime.
This is an excellent solution. I believe that there are use cases where converting to Pascal case is acceptable practice. In my case, one property on a class was dynamic. The result was pascal case for non dynamic types, and camel case for the dynamic and it's sub properties. I also modified the 'CanConvert' method to use 'return (objectType == typeof(Object));', enabling mapping to dynamic properties.
The default for .NET Core 1.0 is now to convert PascalCase C# properties to camelCase json properties, which gives new relevance to this answer and I think it is very relevant.
3

I can't help but feel that this isn't a good idea. It seems like you're trying to preserve a coding convention, but at the expense of maintaining fidelity between the wire format (the JSON structs) and your logic classes. This can cause confusion for developers who expect the JSON classes to be preserved, and might cause issues if you also need, or will need in the future, to re-serialize this data into the same JSON format.

That said, this probably can be achieved by creating the .NET classes ahead of time, then using the DeserializeObject(string value, JsonSerializerSettings settings) overload, passing it a JsonSerializerSettings with the Binder property set. You will also need to write a custom SerializationBinder in which you manually define the relationship between your JSON class and your predefined .NET class.

It may be possible to generate Pascal-cased classes in runtime without predefining them, but I haven't delved deep enough into the JSON.NET implementation for that. Perhaps one of the other JsonSerializerSettings settings, like passing a CustomCreationConverter, but I'm not sure of the details.

3 Comments

Although I did not ask whether it was a good idea to do this or not, both you and Martjin mentioned that it wasn't... so is it because it's dynamic? If I deserialized to public class { public string SomeProperty { get; set; } } would you still feel it was a bad idea and prefer lower camel case for the property (someProperty)?
The coding convention already exists when you decided to deserialize into a Contract. Nevertheless the default MVC binder today is case insensitive.
The capitalization convention for properties in the .NET is PascalCase while the convention for the system I'm getting the JSON from happen to be camelCase. I think converting to PascalCase is the best approach and I was just surprised that so many of you was against it.
1

For newtonsoft add this attribute to your properties:

[JsonProperty("schwabFirmId")]

A simpler option (since you just need to do it once per class) if you are up for including MongoDB: try adding a reference to MongoDB.Bson.Serialization.Conventions.

Then add this in your model constructor:

var pack = new ConventionPack { new CamelCaseElementNameConvention(), new IgnoreIfDefaultConvention(true) };
            ConventionRegistry.Register("CamelCaseIgnoreDefault", pack, t => true);

Either one will keep your favorite C# properties PascalCased and your json camelCased.

Deserializing will treat the inbound data as PascalCased and serializing will change it into camelCase.

Comments

0

This is super old, but I looked at this recently trying to figure it out and was not happy with the answers I found, so i summarized the options and added them bellow.

Dot.net 2.0

       [JsonProperty("baseUrl")]
       public string BaseUrl { get; set; }

Dot.net 3.0+

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
       string json = @"
       {
           ""wsUrl"": ""http://example.com"",
           ""environment"": ""test"",
           ""domain"": ""example""
       }";

       var settings = new JsonSerializerSettings
       {
           ContractResolver = new CamelCasePropertyNamesContractResolver()
       };

       var myObject = JsonConvert.DeserializeObject<MyClass>(json, settings);

In Mvc 6:

services.AddMvc(...)
.AddJsonOptions(jsonOptions =>
{
jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.