Skip to content

Instantly share code, notes, and snippets.

@tangdf
Last active December 29, 2017 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tangdf/00b0ce678c6e1a261d9e0521dc8c1d57 to your computer and use it in GitHub Desktop.
Save tangdf/00b0ce678c6e1a261d9e0521dc8c1d57 to your computer and use it in GitHub Desktop.
字符串序列化,去空格
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Xunit;
using Xunit.Abstractions;
namespace UnitTest
{
public class String_Serialize_Test
{
private ITestOutputHelper _testOutputHelper;
public String_Serialize_Test(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}
[Fact]
public void Serialize()
{
var obj = new {
string1 = "1",
string2 = " 1 ",
string3 = (string) null
};
var json = JsonConvert.SerializeObject(obj, StringJsonConverter.Instance);
Assert.Equal(@"{""string1"":""1"",""string2"":""1"",""string3"":null}", json);
}
}
internal sealed class StringJsonConverter : JsonConverter
{
public static readonly JsonConverter Instance = new StringJsonConverter();
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
string stringValue = (string) value;
if (string.IsNullOrEmpty(stringValue) == false)
stringValue = stringValue.Trim();
writer.WriteValue(stringValue);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override bool CanRead
{
get { return false; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment