How to serialize a JObject the same way as an object with Json.NET?

前端 未结 3 1823
一整个雨季
一整个雨季 2021-01-11 19:24

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

3条回答
  •  有刺的猬
    2021-01-11 20:10

    A solution that well integrates with NewtonSoft framework is to provide a custom JObject converter that honours the NamingStrategy.

    JObject Custom Converter

    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 ();
    }
    }
    

    Usage

    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.

提交回复
热议问题