How do I control the serialization of a JObject to string?
I have some APIs that return a JObject and I usually apply some changes and persist or return them. I want
A solution that well integrates with NewtonSoft framework is to provide a custom JObject converter that honours the NamingStrategy
.
public class JObjectNamingStrategyConverter : JsonConverter {
private NamingStrategy NamingStrategy { get; }
public JObjectNamingStrategyConverter (NamingStrategy strategy) {
if (strategy == null) {
throw new ArgumentNullException (nameof (strategy));
}
NamingStrategy = strategy;
}
public override void WriteJson (JsonWriter writer, JObject value, JsonSerializer serializer) {
writer.WriteStartObject ();
foreach (JProperty property in value.Properties ()) {
var name = NamingStrategy.GetPropertyName (property.Name, false);
writer.WritePropertyName (name);
serializer.Serialize (writer, property.Value);
}
writer.WriteEndObject ();
}
public override JObject ReadJson (JsonReader reader, Type objectType, JObject existingValue, bool hasExistingValue, JsonSerializer serializer) {
throw new NotImplementedException ();
}
}
var snakeNameStrategy = new SnakeCaseNamingStrategy ();
var jsonSnakeSettings = new JsonSerializerSettings {
Formatting = Formatting.Indented,
Converters = new [] { new JObjectNamingStrategyConverter (snakeNameStrategy) },
ContractResolver = new DefaultContractResolver {
NamingStrategy = snakeNameStrategy
},
};
var json = JsonConvert.SerializeObject (obj, jsonSnakeSettings);
You can find a working PoC on GitHub.