Last active
January 13, 2020 06:47
-
-
Save hikipuro/fe8190395c9241fc6984f4bec10fdc20 to your computer and use it in GitHub Desktop.
.NET 4.5: JSON serializer ignore __type property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Runtime.Serialization; | |
using System.Runtime.Serialization.Json; | |
using System.Text; | |
public class ToJsonSample { | |
public string ToJson(Type type, object value) { | |
if (value == null) { | |
return null; | |
} | |
using (MemoryStream stream = new MemoryStream()) | |
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { | |
var settings = new DataContractJsonSerializerSettings(); | |
settings.EmitTypeInformation = EmitTypeInformation.Never; | |
var serializer = new DataContractJsonSerializer(type, settings); | |
serializer.WriteObject(stream, value); | |
stream.Position = 0; | |
return reader.ReadToEnd(); | |
} | |
} | |
public string ToJson<T>(T value) where T : class { | |
if (value == null) { | |
return null; | |
} | |
using (MemoryStream stream = new MemoryStream()) | |
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { | |
var settings = new DataContractJsonSerializerSettings(); | |
settings.EmitTypeInformation = EmitTypeInformation.Never; | |
var serializer = new DataContractJsonSerializer(typeof(T), settings); | |
serializer.WriteObject(stream, value); | |
stream.Position = 0; | |
return reader.ReadToEnd(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment