CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/57987021/remove-replace-newline-character-from-json-in-net-using-jsonconvert
public class ReplacingStringWritingConverter : JsonConverter
{
readonly string oldValue;
readonly string newValue;
public ReplacingStringWritingConverter(string oldValue, string newValue)
{
if (string.IsNullOrEmpty(oldValue))
throw new ArgumentException("string.IsNullOrEmpty(oldValue)");
if (newValue == null)
throw new ArgumentNullException("newValue");
this.oldValue = oldValue;
this.newValue = newValue;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanRead { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var s = ((string)value).Replace(oldValue, newValue);
writer.WriteValue(s);
}
}
class TestClass
{
public static void Test()
{
Test<JToken>();
}
public static void Test<RootObject>()
{
var root = JsonConvert.DeserializeObject<RootObject>(GetJson());
var settings = new JsonSerializerSettings { Converters = { new ReplacingStringWritingConverter("\n", "") } };
var newJson = JsonConvert.SerializeObject(root, Formatting.None, settings);
Console.WriteLine(newJson);
// Assert the JSON string does not contain an escaped newline.
Assert.IsTrue(!newJson.Contains("\\n"));
var newJsonWithoutReplacing = JsonConvert.SerializeObject(root, Formatting.None);
// Assert the default JSON serialization (i.e. without using the converter) does contain an escaped newline
Assert.IsTrue(newJsonWithoutReplacing.Contains("\\n"));
}
static string GetJson()
{
var 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""
}
";
return json;
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
public static string GetNetCoreVersion()
{
//https://techblog.dorogin.com/how-to-detect-net-core-version-in-runtime-ecd65ad695be
//
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];
return null;
}
}