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"));
JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.
Deserializes the JSON to the specified . NET type. Deserializes the JSON to the specified . NET type using a collection of JsonConverter.
SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With