Pages - Menu

Tuesday, March 14, 2017

JSON.net snake case notation naming strategy

Communicating with backend in JSON can be challenging.
In case of C# model which by convention should be in CamelCase notation and backend which is using snake_notation we can easily solve the problem with Json.NET.

For example, we have the next model:

public class Model
{
  public string FooBar { get; set; }
}

and we want it to be serialised to: { "foo_bar": "" }
We could use an attribute:

[JsonProperty(PropertyName = "foo_bar")]
public string FooBar { get; set; }

That will work, however, if we want to generalise this strategy we should create a JsonSerializerSettings with DefaultContactResolver which is using SnakeCaseNamingStrategy and to use it while serialisation/deserialization:

public class JsonCoverter : IJsonConverter
{
 private static JsonSerializerSettings defaultJsonSerializerSettings = 
new JsonSerializerSettings
 {
  ContractResolver = new DefaultContractResolver
  {
   NamingStrategy = new SnakeCaseNamingStrategy()
  }
 };
    
 public T Deserialize<T>(string json) =>
  JsonConvert.DeserializeObject<T>(json, defaultJsonSerializerSettings);
      
 public string Serialize(object obj) =>
  JsonConvert.SerializeObject(obj, defaultJsonSerializerSettings);
   
}

Using the JsonConverter globally will solve the different notation problem.

2 comments:

  1. isn't it snake_notation kebab-notation?

    ReplyDelete
    Replies
    1. Hello, thanks for your comment.
      Yes, you are right! Snake_notation is different from kebab-notation.
      I edited the post accordingly.

      Delete