Every developer must have used JSON
in their life. Json.NET
Was the library that Microsoft used in there every framework from Mobile to Web. Now Microsoft has released their own library for JSON that is written from scratch and very performant. In this article, I will show you about NEW API.
Let’s start with a basic example. Consider the following example. In this example, I am serializing a POCO class to JSON.
Serialize POCO to JSON
void Main()
{
var response = new ResponseJson
{
Status = true,
Message = "my message",
LogId = "my log id",
LogStatus = "my log status"
};
var json = JsonSerializer.Serialize(response);
Console.WriteLine("Serialized {0}", response);
Console.WriteLine(json);
}
public class ResponseJson
{
public bool Status { get; set; }
public string Message { get; set; }
public string LogId { get; set; }
public string LogStatus { get; set; }
}
Serialized ResponseJson
{"Status":true,"Message":"my message","LogId":"my log id","LogStatus":"my log status"}
Customize property names
As you can see above, that JSON property name is the same as the C# property name. If you want to control the name of JSON property, you can use the JsonPropertyName
attribute as shown below{alertInfo}
public class ResponseJson
{
[JsonPropertyName("status")]
public bool Status { get; set; }
[JsonPropertyName("message")]
public string Message { get; set; }
[JsonPropertyName("Log_id")]
public string LogId { get; set; }
[JsonPropertyName("Log_status")]
public string LogStatus { get; set; }
}
output
Serialized ResponseJson
{"status":true,"message":"my message","Log_id":"my log id","Log_status":"my log status"}
How to Deserialize JSON to POCO
{
"status":true,
"message":"my message",
"Log_id":"my log id",
"Log_status":"my log status"
}
void Main()
{
var jsonResponse="{\"Status\":true,\"Message\":\"my message\",\"LogId\":\"my log id\",\"LogStatus\":\"my log status\"}";
var json = JsonSerializer.Deserialize<ResponseJson>(jsonResponse);
Console.WriteLine("Serialized {0}", json);
Console.WriteLine(json);
}
How to print Indented JSON
If you want to print indented JSON output, then you can pass JsonSerializerOptions
and set the property WriteIndented=true
void Main()
{
var response = new ResponseJson
{
Status = true,
Message = "my message",
LogId = "my log id",
LogStatus = "my log status",
FailureReason = "my failure reason"
};
var options = new JsonSerializerOptions
{
WriteIndented = true,
};
var json = JsonSerializer.Serialize(response, options);
Console.WriteLine("Serialized {0}", response);
Console.WriteLine(json);
}
{
"Status": true,
"Message": "my message",
"LogId": "my log id",
"LogStatus": "my log status",
"FailureReason": "my failure reason"
}
Camel case for all JSON property names
When you are sending JSON
to WEB application then you need to use camelCase for JSON
property. Simply set PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
in JsonSerializerOptions
option
void Main()
{
var response = new ResponseJson
{
Status = true,
Message = "my message",
LogId = "my log id",
LogStatus = "my log status"
};
var serializeOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
var json = JsonSerializer.Serialize(response, serializeOptions);
Console.WriteLine("Serialized {0}", response);
Console.WriteLine(json);
}
Serialized ResponseJson
{
"status": true,
"message": "my message",
"logId": "my log id",
"logStatus": "my log status"
}
Use a custom JSON property naming policy
Assume if you want to change the JSON
property name before sending it to the server. You can do it easily with the Microsoft JSON library.
Step1
-Create a custom class and Implements theJsonNamingPolicy
abstract class, which has one abstract method, ConvertName.
Write the transformation logic(In this example, I am converting the name to snake case)
public class SnakeNamePolicy : JsonNamingPolicy
{
public override string ConvertName(string name)
{
return ToUnderscoreCase(name);
}
private string ToUnderscoreCase(string str)
=> string.Concat((str ?? string.Empty).Select((x, i) => i > 0 && char.IsUpper(x) && !char.IsUpper(str[i - 1]) ? $"_{x}" : x.ToString())).ToLower();
}
Step2
Pass the newly created policy to JsonSerializerOptions
and then in the Serialize
method.
void Main()
{
var response = new ResponseJson
{
Status = true,
Message = "my message",
LogId = "my log id",
LogStatus = "my log status"
};
var serializeOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = new SnakeNamePolicy(),
WriteIndented = true
};
var json = JsonSerializer.Serialize(response, serializeOptions);
Console.WriteLine("Serialized {0}", response);
Console.WriteLine(json);
}
Output
Serialized ResponseJson
{
"status": true,
"message": "my message",
"log_id": "my log id",
"log_status": "my log status"
}
Convert Enum to String
Usually, when you serialize a class with an enum, the serialized value has the numeric value of the enum. Still, In the Microsoft JSON library, you have the option to convert it to string. Add the following setting to the serialization options.
var serializeOptions = new JsonSerializerOptions
{
Converters =
{
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)
}
};
public class ResponseJson
{
public bool Status { get; set; }
public string Message { get; set; }
public string LogId { get; set; }
public string LogStatus { get; set; }
public Severity Severity { get; set; }
}
public enum Severity
{
Low,
High,
Critical
}
void Main()
{
var response = new ResponseJson
{
Status = true,
Message = "my message",
LogId = "my log id",
LogStatus = "my log status",
Severity = Severity.Critical
};
var serializeOptions = new JsonSerializerOptions
{
Converters =
{
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)
}
};
var json = JsonSerializer.Serialize(response, serializeOptions);
Console.WriteLine("Serialized {0}", response);
Console.WriteLine(json);
}
output
Serialized ResponseJson
{"Status":true,"Message":"my message","LogId":"my log id","LogStatus":"my log status","Severity":"critical"}
Ignore Property
Sometimes, suppose you want to ignore some property like Password, credit card number. In that case, you can add the JsonIgnore
attribute to your property. The serializer will ignore these properties.
Use JsonIgnore
to ignore the property.
Ignore Read-Only Properties
Sometimes, suppose you want to ignore some property like Password, credit card number. In that case, you can add the JsonIgnore
attribute to your property. The serializer will ignore these properties.
use IgnoreReadOnlyProperties
var options = new JsonSerializerOptions
{
IgnoreReadOnlyProperties = true,
WriteIndented = true
};
jsonString = JsonSerializer.Serialize(weatherForecast, options);
Convert Property Value while Serializing
This is a compelling feature of the Microsoft Serializer library. Let’s suppose you want to serialize a property, but you want to do some preprocessing before that. In this example, I am converting the string to Base64.
void Main()
{
var response = new ResponseJson
{
Status = true,
Message = "my message",
LogId = "my log id",
LogStatus = "my log status",
Severity = Severity.Critical
};
var json = JsonSerializer.Serialize(response);
Console.WriteLine("Serialized {0}", response);
Console.WriteLine(json);
}
public class StringToBase64JsonConvertor : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.GetString().ToLower();
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
writer.WriteBase64StringValue(Encoding.UTF8.GetBytes(value));
}
}
public class ResponseJson
{
public bool Status { get; set; }
public string Message { get; set; }
public string LogId { get; set; }
[JsonConverter(typeof(StringToBase64JsonConvertor))]
public string LogStatus { get; set; }
public Severity Severity { get; set; }
}
public enum Severity
{
Low,
High,
Critical
}
Output
Serialized ResponseJson
{"Status":true,"Message":"my message","LogId":"my log id","LogStatus":"bXkgbG9nIHN0YXR1cw==","Severity":2}