I need to remove some newline characters from some string values while serializing to JSON -- i.e. during c# object to JSON conversion. How can this be done?
public static string ToJson(this object value)
{
//Serializing C# Object to Json which gives me below mentioned JSON.
return JsonConvert.SerializeObject(value);
}
Below is my sample JSON:
{
"PolicyHolderInfo": {
"ActionDate": "20190912",
"EmployeeCode": "EPL2",
"LocalEntityCode": "K",
"PolicyHolderCode": "1YAAAAC",
"Name1": "monoliability PDL\n",
"Name2": "test\n",
"Street1": "-",
"Street2": "-",
"City": "-",
"PostCode": "-",
"Subdivision": "01",
"FMEPaymentFrequency1": "00",
"Reference": "C00-AAC"
},
"PolicyHolderTrailerInfo": {
"RecordCode": "Z",
"CountryCode": "KSA",
"SourceIndicator": "EPLC",
"RecordSequence": 0,
"LinkNumber": 0,
"RecordType": "Z",
"ReturnCode": null,
"Reference": "1-AC"
},
"SourceSystemDate": "2019-09-17T17:48:31.3543314+08:00"
}
The Name1 and Name2 has newline character \n. I tried many options to remove those \n. Instead of looping through every value, I am just trying to replace globally if any new line characters present. None of the below options are working?
C#:
var str1 = JsonConvert.ToString(value);
var str2 = value.Replace(System.Environment.NewLine, string.Empty);
Regex regex_newline = new Regex("(\r\n|\r|\n)");
var str3 = regex_newline.Replace(value, "");
var str4 = value.Replace("\n", string.Empty);
The 'value' in above code is json mentioned in the sample.