JSON Change Name of Field or Property Serialization
Overview
In this tutorial, we shall see how to change the name of a field to map to another JSON property on serialization in C# or .NET Codebase.
We shall see how to use [JsonPropertyName(“”)] attribute which helps to serialize or deserializing the property name that is present in the JSON This way you are able to override any naming policy available by default.
Today in this article, we will cover below aspects,
You might find multiple needs to map a field to a different property while performing serialization or de-serialization.
JsonPropertyName in NewtonSoft Vs System.Text.Json
JsonPropertyName attribute is available in both Newtonsoft.Json and System.Text.Json and provides the same ability to override the property name.
I have simple class Entity as shown below,
public partial class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string ZipCode { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string EmployeeId { get; set; }
}
If this is serialized to JSON, below is the output we shall get,
Example
NewtonSoft.JSON
JsonConvert.SerializeObject(emp);
System.Text.Json
JsonSerializer.Serialize(emp)
JSON output
Using above both ways we get below JSON output,
{
"FirstName": "ABCD",
"LastName": "TEST",
"Address": "USA",
"ZipCode": "123",
"State": "CA",
"Country": "USA",
"EmployeeId": "1111"
}
Using JsonPropertyNameAttribute annotation
Lets now customize the property field output.
Let’s say you want “First_Name” and “Last_Name” as the property field instead of the old ones.
In such case , please use JsonProperty attribute annotation as below,
The generated Entity would now look as below,
{
"First_Name": "ABCD",
"Last_Name": "TEST",
"Address": "USA",
"ZipCode": null,
"State": "CA",
"Country": null,
"EmployeeId": "1111"
}
Please note that JsonPropertyNameAttribute is available for both JSON.NET(Newtonsoft) and System.Text.Json
As per Microsoft,
A property value enclosed in single quotes will result in a JsonException. System.Text.Json shall accept property names and string values only in double-quotes as per RFC 8259 specification.
References:
Summary
JsonPropertyNameAttribute helps you overriding the property name that is present in the JSON when serializing and deserializing in a simple way using attribute annotation.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.