'How to make serialized object string in serialized object readable with avoiding \u0022 characters in C#?
I am serializing an object with JsonSerializer and assign this string into another object's property. Then I am serializing this parent object again and writing to a file. But there are so many characters like \u0022, \u002B etc. Is there a way to make this inner serialized object string looks pretty and readable that doesn't contain these unreadable characters? (One possible option; replacing these characters with empty string, because I need to deserialize it somewhere else)
Parent class:
public class LogItem
{
public string Application { get; set; } = "";
public string AdditionalInfo { get; set; } = "";
public ResponseLogItem Response { get; set; } = new();
public RequestLogItem Request { get; set; } = new();
}
AdditionalInfo is a serialized object string of this class:
public class IncomingMessage
{
public string time { get; set; }
public string type { get; set; }
public string description { get; set; }
public string from { get; set; }
public string to { get; set; }
public Message message { get; set; }
}
Here is my code:
var options = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
WriteIndented = true
};
var messageString = JsonSerializer.Serialize(incomingMessage);
var messageLog = new()
{
Application = "Message", AdditionalInfo = messageString
};
var fileName = "messageLog.txt";
textLogger.Log(messageLog, fileName, token);
This textLogger is another service for writing logs.
Here is log file:
{
"Application": "Message",
"AdditionalInfo": "{\r\n \u0022time\u0022: \u00222022-05-03T16:48:12.4957321Z\u0022,\r\n \u0022type\u0022: \u0022message-received\u0022,\r\n \u0022description\u0022: \u0022Test\u0022,\r\n \u0022from\u0022: \u0022\u002B90555555555\u0022,\r\n \u0022to\u0022: \u0022\u002B90555555556\u0022,\r\n \u0022message\u0022: {\r\n \u0022id\u0022: \u0022abc1239\u0022,\r\n \u0022time\u0022: \u00222022-05-03T16:48:12.4957321Z\u0022,\r\n \u0022text\u0022: \u0022Test 3\u0022,\r\n \u0022applicationId\u0022: \u00220a1ea845\u0022,\r\n \u0022direction\u0022: \u0022in\u0022,\r\n}\r\n}",
"Response": {
"StatusCode": "",
"Duration": "0",
"Body": "",
"HeaderJson": ""
},
"Request": {
"QueryString": "",
"Body": "",
"Scheme": "",
"Path": "",
"Host": "",
"Method": "",
"ReceptionDate": null,
"HeaderJson": "",
"Ip": "",
"Environment": "",
"User": ""
} }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
