Reputation: 9509
Say i have a JRaw
property where i place a Pascal cased JSON into.
public class C
{
public JRaw Prop {get;set;}
}
var a = new JRaw("{\"A\":42}");
var c = new C { Prop = a };
Now when i serialize this i can force c
to be lowercase, like so:
var result = JsonConvert.SerializeObject(c, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
// i have "{\"c\":{\"A\":42}}"
However, is there any way to make JRaw
also camelcased?
e.g. i want to get
// "{\"c\":{\"a\":42}}"
Upvotes: 1
Views: 676
Reputation: 2642
Here's a way to do it although it may not be the most efficient as it requires you to serialize your object, deserialize, then serialize it again. I believe the problem is the serializer is not detecting your "A" JSON property properly since it's a raw JSON string as opposed to an object property. This will convert your JRaw JSON string to a dynamic object (ExpandoObject
) allowing the "A" JSON property to become an object property temporarily. This'll then be picked up by the serializer once the object is serialized, resulting in all nested property keys being camel case.
using System;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System.Dynamic;
public class Program
{
public class C
{
public JRaw Prop { get; set; }
}
public static void Main()
{
var a = new JRaw("{\"A\":42}");
var c = new C { Prop = a };
var camelCaseSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var result = JsonConvert.SerializeObject(c, camelCaseSettings);
var interimObject = JsonConvert.DeserializeObject<ExpandoObject>(result);
result = JsonConvert.SerializeObject(interimObject, camelCaseSettings);
Console.WriteLine(result);
Console.ReadKey();
}
}
Output: {"prop":{"a":42}}
Upvotes: 1