Skip to content

Instantly share code, notes, and snippets.

@hikipuro
Last active January 13, 2020 06:47
Show Gist options
  • Save hikipuro/fe8190395c9241fc6984f4bec10fdc20 to your computer and use it in GitHub Desktop.
Save hikipuro/fe8190395c9241fc6984f4bec10fdc20 to your computer and use it in GitHub Desktop.
.NET 4.5: JSON serializer ignore __type property
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