DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

Why we JsonProperty For Mapping of data With Example

JsonProperty is an attribute in C# (and other programming languages) that allows developers to control the mapping between property names and JSON keys when serializing or deserializing objects. It is often used in conjunction with JSON frameworks such as Newtonsoft.Json.

Here's an example to illustrate the usage of JsonProperty:

Let's say we have a class called Person that represents a person with various properties like Name, Age, and EmailAddress. We want to serialize an instance of this class to JSON, but we want the JSON key for the EmailAddress property to be named "email" instead of "EmailAddress".

using Newtonsoft.Json;

public class Person
{
    public string Name { get; set; }

    public int Age { get; set; }

    [JsonProperty("email")]
    public string EmailAddress { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

In the example above, we have decorated the EmailAddress property with the [JsonProperty("email")] attribute. This attribute tells the JSON serializer to use the key "email" instead of "EmailAddress" when serializing or deserializing JSON.

Now, let's serialize an instance of the Person class to JSON:

Person person = new Person
{
    Name = "John Doe",
    Age = 30,
    EmailAddress = "johndoe@example.com"
};

string json = JsonConvert.SerializeObject(person);
Enter fullscreen mode Exit fullscreen mode

The resulting JSON would be:

{
    "Name": "John Doe",
    "Age": 30,
    "email": "johndoe@example.com"
}
Enter fullscreen mode Exit fullscreen mode

As you can see, the EmailAddress property was serialized as "email" in the JSON due to the [JsonProperty("email")] attribute.

JsonProperty can also be used during deserialization, allowing you to map JSON keys to property names. This way, you can handle cases where the JSON key differs from the property name in your.

JsonProperty is used to control the mapping between property names and JSON keys during serialization and deserialization, providing flexibility in working with JSON data.

Top comments (0)