How to apply indenting serialization only to some properties? - c#

I want to serialize .NET objects to JSON in a human-readable way, but I would like to have more control about whether an object's properties or array's elements end up on a line of their own.
Currently I'm using JSON.NET's JsonConvert.SerializeObject(object, Formatting, JsonSerializerSettings) method for serialization, but it seems I can only apply the Formatting.Indented (all elements on individual lines) or Formatting.None (everything on a single line without any whitespace) formatting rules globally for the entire object. Is there a way to globally use indenting by default, but turn it off for certain classes or properties, e.g. using attributes or other parameters?
To help you understand the problem, here are some output examples. Using Formatting.None:
{"array":["element 1","element 2","element 3"],"object":{"property1":"value1","property2":"value2"}}
Using Formatting.Indented:
{
"array": [
"element 1",
"element 2",
"element 3"
],
"object": {
"property1": "value1",
"property2":"value2"
}
}
What I would like to see:
{
"array": ["element 1","element 2","element 3"],
"object": {"property1":"value1","property2":"value2"}
}
(I realize my question may be slightly related to this one, but the comments there totally miss the point and don't actually provide a valid answer.)

One possibility would be to write a custom Json converter for the specific types you need special handling and switch the formatting for them:
class Program
{
static void Main()
{
var root = new Root
{
Array = new[] { "element 1", "element 2", "element 3" },
Object = new Obj
{
Property1 = "value1",
Property2 = "value2",
},
};
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
};
settings.Converters.Add(new MyConverter());
string json = JsonConvert.SerializeObject(root, settings);
Console.WriteLine(json);
}
}
public class Root
{
public string[] Array { get; set; }
public Obj Object { get; set; }
}
public class Obj
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
class MyConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string[]) || objectType == typeof(Obj);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue(JsonConvert.SerializeObject(value, Formatting.None));
}
}
This will output:
{
"Array": ["element 1","element 2","element 3"],
"Object": {"Property1":"value1","Property2":"value2"}
}

I also used a converter for this (as per Darin Dimitrov's answer), but instead of calling WriteRawValue() I use the serializer for each element; which ensures any custom converters that apply to the element type will be used.
Note however that this converter is only operating on Arrays of a handful of primitive types, it's not using the Newtonsoft.Json logic for determining what should be serialized as an array and what a primitive type is, basically because that code is internal and I wanted to avoid maintaining a copy of it.
Overall I get the feeling that converters aren't intended to be used for formatting tasks such as this, but I think they're the only option in the current API. Ideally the API would offer a few more formatting options or perhaps better support for custom formatting within the converter API.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace JsonProto
{
/// <summary>
/// A JsonConverter that modifies formatting of arrays, such that the array elements are serialised to a single line instead of one element per line
/// preceded by indentation whitespace.
/// This converter handles writing JSON only; CanRead returns false.
/// </summary>
/// <remarks>
/// This converter/formatter applies to arrays only and not other collection types. Ideally we would use the existing logic within Newtonsoft.Json for
/// identifying collections of items, as this handles a number of special cases (e.g. string implements IEnumerable over the string characters). In order
/// to avoid duplicating in lots of logic, instead this converter handles only Arrays of a handful of selected primitive types.
/// </remarks>
public class ArrayNoFormattingConverter : JsonConverter
{
# region Static Fields
static HashSet<Type> _primitiveTypeSet =
new HashSet<Type>
{
typeof(char),
typeof(char?),
typeof(bool),
typeof(bool?),
typeof(sbyte),
typeof(sbyte?),
typeof(short),
typeof(short?),
typeof(ushort),
typeof(ushort?),
typeof(int),
typeof(int?),
typeof(byte),
typeof(byte?),
typeof(uint),
typeof(uint?),
typeof(long),
typeof(long?),
typeof(ulong),
typeof(ulong?),
typeof(float),
typeof(float?),
typeof(double),
typeof(double?),
typeof(decimal),
typeof(decimal?),
typeof(string),
typeof(DateTime),
typeof(DateTime?),
};
#endregion
#region Properties
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
// Note. Ideally this would match the test for JsonContractType.Array in DefaultContractResolver.CreateContract(),
// but that code is all internal to Newtonsoft.Json.
// Here we elect to take over conversion for Arrays only.
if(!objectType.IsArray) {
return false;
}
// Fast/efficient way of testing for multiple possible primitive types.
Type elemType = objectType.GetElementType();
return _primitiveTypeSet.Contains(elemType);
}
/// <summary>
/// Gets a value indicating whether this <see cref="JsonConverter"/> can read JSON.
/// </summary>
/// <value>Always returns <c>false</c>.</value>
public override bool CanRead
{
get { return false; }
}
#endregion
#region Public Methods
/// <summary>
/// Reads the JSON representation of the object. (Not implemented on this converter).
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Formatting formatting = writer.Formatting;
writer.WriteStartArray();
try
{
writer.Formatting = Formatting.None;
foreach(object childValue in ((System.Collections.IEnumerable)value)) {
serializer.Serialize(writer, childValue);
}
}
finally
{
writer.WriteEndArray();
writer.Formatting = formatting;
}
}
#endregion
}
}

Related

OrderedDictionary is not being saved when saving Settings

In my application I've implemented a few Controls to browse data in different ways. In every Control I display a TreeView to allow the user to go from a folder to another.
I would like my Controls to "remember" the last selected tree, in a generic way (I mean that if, in the future I add another Control I don't want to do a lot of adaptations). So I added an OrderedDictionary in the Settings. I use the Control's Type Name as a key and the Node's path as value.
As I was unable to set a default value for this dictionary I used this trick:
Settings.cs :
public OrderedDictionary Paths
{
get
{
return LastsPaths ?? (LastsPaths = new OrderedDictionary());
}
set
{
this["LastsPaths"] = value;
}
}
Settings.Designer.cs:
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.Collections.Specialized.OrderedDictionary LastsPaths {
get {
return ((global::System.Collections.Specialized.OrderedDictionary)(this["LastsPaths"]));
}
set {
this["LastsPaths"] = value;
}
}
I do call Save each time I add/update a value, the user.config file timestamps change, but the content stays the same:
<setting name="LastsPaths" serializeAs="Xml">
<value />
</setting>
It doesn't work with:
App in debug mode;
App in release mode;
App installed.
How can I fix this?
It seems OrderedDictionary (and generic dictionaries in general) are not XML serializable.
You can wrap it in another class that does the serialization manually. In that way you don't expose the dictionary directly to the XML serializer. You have to implement IXmlSerializable to achieve this.
This might be enough to get you started. This inherits IXMLSerializable which is needed during the Save call.
[XmlRoot("PreviouslyVisitedPaths")]
public class PreviouslySelectedPaths : OrderedDictionary, IXmlSerializable
{
#region Implementation of IXmlSerializable
/// <summary>
/// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class.
/// </summary>
/// <returns>
/// An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.
/// </returns>
public XmlSchema GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized. </param>
public void ReadXml(XmlReader reader)
{
var keySerializer = new XmlSerializer(typeof(object));
var valueSerializer = new XmlSerializer(typeof(object));
var wasEmpty = reader.IsEmptyElement;
reader.Read();
if(wasEmpty)
{
return;
}
while(reader.NodeType != XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
var key = keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
var value = valueSerializer.Deserialize(reader);
reader.ReadEndElement();
Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized. </param>
public void WriteXml(XmlWriter writer)
{
var keySerializer = new XmlSerializer(typeof(object));
var valueSerializer = new XmlSerializer(typeof(object));
foreach(var key in Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
var value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
#endregion
}
}
You would then change your code to this:
public PreviouslySelectedPaths Paths
{
get
{
return LastsPaths ?? (LastsPaths = new PreviouslySelectedPaths());
}
set
{
this["LastsPaths"] = value;
}
}
You would also need to make LastsPaths type PreviouslySelectedPaths.
This is just to get your started you may need to tweek the IXMLSerializable methods and fill in logic for GetSchema().

DeSerialize JSON into C# Object: How to Handle Missing properties

I have a problem, my JSON object does not contain all the properties which are available in C# object (DataMember).
Is there any way I can ignore missing properties while deserializing JSON
/// <summary>
/// Deserializes a stream that contains a json text into an object.
/// </summary>
/// <typeparam name="T">The type of the object to be deserialized into.</typeparam>
/// <param name="stream">The stream that contains the json text representation of the object.</param>
/// <returns>A deserialized object.</returns>
public static T DeserializeJson<T>(Stream stream) where T : class
{
DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T), settings);
return jsonSerializer.ReadObject(stream) as T;
}
You can specify IsRequired property for DataMemberAttribute.
If you set it to false, deserialisation won't throw exception if this member is missing in your json.
[DataMember( IsRequired = false )]
public bool ManualSessionClose { get; set; }

Pascal case dynamic properties with Json.NET

This is what I have:
using Newtonsoft.Json;
var json = "{\"someProperty\":\"some value\"}";
dynamic deserialized = JsonConvert.DeserializeObject(json);
This works fine:
Assert.That(deserialized.someProperty.ToString(), Is.EqualTo("some value"));
I want this to work (first letter of properties upper-cased) without changing json:
Assert.That(deserialized.SomeProperty.ToString(), Is.EqualTo("some value"));
I agree with Avner Shahar-Kashtan. You shouldn't be doing this, especially if you have no control over the JSON.
That said, it can be done with the use of a ExpandoObject and a custom ExpandoObjectConverter. JSON.NET already provides a ExpandoObjectConverter so with some little adjustments you have what you want.
Notice the //CHANGED comments inside the code snippet to show you where I changed it.
public class CamelCaseToPascalCaseExpandoObjectConverter : JsonConverter
{
//CHANGED
//the ExpandoObjectConverter needs this internal method so we have to copy it
//from JsonReader.cs
internal static bool IsPrimitiveToken(JsonToken token)
{
switch (token)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
return true;
default:
return false;
}
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// can write is set to false
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return ReadValue(reader);
}
private object ReadValue(JsonReader reader)
{
while (reader.TokenType == JsonToken.Comment)
{
if (!reader.Read())
throw new Exception("Unexpected end.");
}
switch (reader.TokenType)
{
case JsonToken.StartObject:
return ReadObject(reader);
case JsonToken.StartArray:
return ReadList(reader);
default:
//CHANGED
//call to static method declared inside this class
if (IsPrimitiveToken(reader.TokenType))
return reader.Value;
//CHANGED
//Use string.format instead of some util function declared inside JSON.NET
throw new Exception(string.Format(CultureInfo.InvariantCulture, "Unexpected token when converting ExpandoObject: {0}", reader.TokenType));
}
}
private object ReadList(JsonReader reader)
{
IList<object> list = new List<object>();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Comment:
break;
default:
object v = ReadValue(reader);
list.Add(v);
break;
case JsonToken.EndArray:
return list;
}
}
throw new Exception("Unexpected end.");
}
private object ReadObject(JsonReader reader)
{
IDictionary<string, object> expandoObject = new ExpandoObject();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
//CHANGED
//added call to ToPascalCase extension method
string propertyName = reader.Value.ToString().ToPascalCase();
if (!reader.Read())
throw new Exception("Unexpected end.");
object v = ReadValue(reader);
expandoObject[propertyName] = v;
break;
case JsonToken.Comment:
break;
case JsonToken.EndObject:
return expandoObject;
}
}
throw new Exception("Unexpected end.");
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
return (objectType == typeof (ExpandoObject));
}
/// <summary>
/// Gets a value indicating whether this <see cref="JsonConverter"/> can write JSON.
/// </summary>
/// <value>
/// <c>true</c> if this <see cref="JsonConverter"/> can write JSON; otherwise, <c>false</c>.
/// </value>
public override bool CanWrite
{
get { return false; }
}
}
A simple string to Pascal Case converter. Make it smarter if you need to.
public static class StringExtensions
{
public static string ToPascalCase(this string s)
{
if (string.IsNullOrEmpty(s) || !char.IsLower(s[0]))
return s;
string str = char.ToUpper(s[0], CultureInfo.InvariantCulture).ToString((IFormatProvider)CultureInfo.InvariantCulture);
if (s.Length > 1)
str = str + s.Substring(1);
return str;
}
}
Now you can use it like this.
var settings = new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter> { new CamelCaseToPascalCaseExpandoObjectConverter() }
};
var json = "{\"someProperty\":\"some value\"}";
dynamic deserialized = JsonConvert.DeserializeObject<ExpandoObject>(json, settings);
Console.WriteLine(deserialized.SomeProperty); //some value
var json2 = JsonConvert.SerializeObject(deserialized, Formatting.None, settings);
Console.WriteLine(json == json2); //true
The ContractResolver CamelCasePropertyNamesContractResolver is used when serializing the object back to JSON and makes it Camel case again. This is also provided by JSON.NET. If you don't need this you can omit it.
I can't help but feel that this isn't a good idea. It seems like you're trying to preserve a coding convention, but at the expense of maintaining fidelity between the wire format (the JSON structs) and your logic classes. This can cause confusion for developers who expect the JSON classes to be preserved, and might cause issues if you also need, or will need in the future, to re-serialize this data into the same JSON format.
That said, this probably can be achieved by creating the .NET classes ahead of time, then using the DeserializeObject(string value, JsonSerializerSettings settings) overload, passing it a JsonSerializerSettings with the Binder property set. You will also need to write a custom SerializationBinder in which you manually define the relationship between your JSON class and your predefined .NET class.
It may be possible to generate Pascal-cased classes in runtime without predefining them, but I haven't delved deep enough into the JSON.NET implementation for that. Perhaps one of the other JsonSerializerSettings settings, like passing a CustomCreationConverter, but I'm not sure of the details.
For newtonsoft add this attribute to your properties:
[JsonProperty("schwabFirmId")]
A simpler option (since you just need to do it once per class) if you are up for including MongoDB: try adding a reference to MongoDB.Bson.Serialization.Conventions.
Then add this in your model constructor:
var pack = new ConventionPack { new CamelCaseElementNameConvention(), new IgnoreIfDefaultConvention(true) };
ConventionRegistry.Register("CamelCaseIgnoreDefault", pack, t => true);
Either one will keep your favorite C# properties PascalCased and your json camelCased.
Deserializing will treat the inbound data as PascalCased and serializing will change it into camelCase.

Is there a way to make JavaScriptSerializer ignore properties of a certain generic type?

I am using the Entity Framework for my models, and i have need to serialize them to JSON. The problem is that EF includes all these really nice navigational collections (For instance my User model has an Orders property on it) and when I go to serialize these objects the serializer tries to get the value for those collections and EF yells at me for trying to use a disposed context
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
I know I can decorate my properties with [ScriptIgnore] to make the serializer leave them alone, but thats a problem with EF as it generates the code for those properties.
Is there a way to make the serializer not serialize properties that are of the generic type EntityCollection<>?
Alternatively is there a way to do this with another robust json library like JSON.Net?
You can declare a custom contract resolver which indicates which properties to ignore. Here's a general-purpose "ignorable", based on the answer I found here:
/// <summary>
/// Special JsonConvert resolver that allows you to ignore properties. See https://stackoverflow.com/a/13588192/1037948
/// </summary>
public class IgnorableSerializerContractResolver : DefaultContractResolver {
protected readonly Dictionary<Type, HashSet<string>> Ignores;
public IgnorableSerializerContractResolver() {
this.Ignores = new Dictionary<Type, HashSet<string>>();
}
/// <summary>
/// Explicitly ignore the given property(s) for the given type
/// </summary>
/// <param name="type"></param>
/// <param name="propertyName">one or more properties to ignore. Leave empty to ignore the type entirely.</param>
public void Ignore(Type type, params string[] propertyName) {
// start bucket if DNE
if (!this.Ignores.ContainsKey(type)) this.Ignores[type] = new HashSet<string>();
foreach (var prop in propertyName) {
this.Ignores[type].Add(prop);
}
}
/// <summary>
/// Is the given property for the given type ignored?
/// </summary>
/// <param name="type"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
public bool IsIgnored(Type type, string propertyName) {
if (!this.Ignores.ContainsKey(type)) return false;
// if no properties provided, ignore the type entirely
if (this.Ignores[type].Count == 0) return true;
return this.Ignores[type].Contains(propertyName);
}
/// <summary>
/// The decision logic goes here
/// </summary>
/// <param name="member"></param>
/// <param name="memberSerialization"></param>
/// <returns></returns>
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) {
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (this.IsIgnored(property.DeclaringType, property.PropertyName)) {
property.ShouldSerialize = instance => { return false; };
}
return property;
}
}
And usage:
var jsonResolver = new IgnorableSerializerContractResolver();
// ignore single property
jsonResolver.Ignore(typeof(Company), "WebSites");
// ignore single datatype
jsonResolver.Ignore(typeof(System.Data.Objects.DataClasses.EntityObject));
var jsonSettings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver };
If the idea is simply to return those objects to the client side why don't you just return what you need using anonymous classes?
Assuming you have this ugly heavy list of EntityFrameworkClass objects, you could do this:
var result = (from c in List<EntityFrameworkClass>
select new {
PropertyINeedOne=c.EntityFrameworkClassProperty1,
PropertyINeedTwo=c.EntityFrameworkClassProperty2
}).ToList();
This is my little contribution. Some changes to #drzaus answer.
Description: Some resharped changes and Fluent enabled. And a little fix to use PropertyType instead of DeclaringType.
public class IgnorableSerializerContractResolver : DefaultContractResolver
{
protected readonly Dictionary<Type, HashSet<string>> Ignores;
public IgnorableSerializerContractResolver()
{
Ignores = new Dictionary<Type, HashSet<string>>();
}
/// <summary>
/// Explicitly ignore the given property(s) for the given type
/// </summary>
/// <param name="type"></param>
/// <param name="propertyName">one or more properties to ignore. Leave empty to ignore the type entirely.</param>
public IgnorableSerializerContractResolver Ignore(Type type, params string[] propertyName)
{
// start bucket if DNE
if (!Ignores.ContainsKey(type))
Ignores[type] = new HashSet<string>();
foreach (var prop in propertyName)
{
Ignores[type].Add(prop);
}
return this;
}
/// <summary>
/// Is the given property for the given type ignored?
/// </summary>
/// <param name="type"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
public bool IsIgnored(Type type, string propertyName)
{
if (!Ignores.ContainsKey(type)) return false;
// if no properties provided, ignore the type entirely
return Ignores[type].Count == 0 || Ignores[type].Contains(propertyName);
}
/// <summary>
/// The decision logic goes here
/// </summary>
/// <param name="member"></param>
/// <param name="memberSerialization"></param>
/// <returns></returns>
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (IsIgnored(property.PropertyType, property.PropertyName))
{
property.ShouldSerialize = instance => false;
}
return property;
}
}
usage:
// Ignore by type, regardless property name
var jsonResolver = new IgnorableSerializerContractResolver().Ignore(typeof(PropertyName))
var jsonSettings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver };
Adding on to #drzaus's answer, I modified the IsIgnored method to make it more generic -
public bool IsIgnored(Type type, string propertyName)
{
var ignoredType = this.Ignores.Keys.FirstOrDefault(t => type.IsSubclassOf(t) || type == t || t.IsAssignableFrom(type));
//if (!this.Ignores.ContainsKey(type)) return false;
if (ignoredType == null) return false;
// if no properties provided, ignore the type entirely
if (this.Ignores[ignoredType].Count == 0) return true;
return this.Ignores[ignoredType].Contains(propertyName);
}
And its usage:
var jsonResolver = new IgnorableSerializerContractResolver();
jsonResolver.Ignore(typeof(BaseClassOrInterface), "MyProperty");
The above helped me make a generic serializer for converting Thrift objects to standard JSON. I wanted to ignore the __isset property while serializing objects of classes that implement the Thrift.Protocol.TBase interface.
Hope it helps.
PS - I know converting a Thrift object to standard JSON defeats its purpose, but this was a requirement for interfacing with a legacy system.
If you use JSON.NET you can use attributes like JsonIgnore to ignore certain properties. I use this feature when serializing objects loaded via NHibernate.
I think there is a possibility to add conventions, too. Maybe you can implement a filter for your EF properties.

Is there a serializable generic Key/Value pair class in .NET?

I'm looking for a key/value pair object that I can include in a web service.
I tried using .NET's System.Collections.Generic.KeyValuePair<> class, but it does not properly serialize in a web service. In a web service, the Key and Value properties are not serialized, making this class useless, unless someone knows a way to fix this.
Is there any other generic class that can be used for this situation?
I'd use .NET's System.Web.UI.Pair class, but it uses Object for its types. It would be nice to use a Generic class, if only for type safety.
Just define a struct/class.
[Serializable]
public struct KeyValuePair<K,V>
{
public K Key {get;set;}
public V Value {get;set;}
}
I don't think there is as Dictionary<> itself isn't XML serializable, when I had need to send a dictionary object via a web service I ended up wrapping the Dictionary<> object myself and adding support for IXMLSerializable.
/// <summary>
/// Represents an XML serializable collection of keys and values.
/// </summary>
/// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of the values in the dictionary.</typeparam>
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
#region Constants
/// <summary>
/// The default XML tag name for an item.
/// </summary>
private const string DEFAULT_ITEM_TAG = "Item";
/// <summary>
/// The default XML tag name for a key.
/// </summary>
private const string DEFAULT_KEY_TAG = "Key";
/// <summary>
/// The default XML tag name for a value.
/// </summary>
private const string DEFAULT_VALUE_TAG = "Value";
#endregion
#region Protected Properties
/// <summary>
/// Gets the XML tag name for an item.
/// </summary>
protected virtual string ItemTagName
{
get
{
return DEFAULT_ITEM_TAG;
}
}
/// <summary>
/// Gets the XML tag name for a key.
/// </summary>
protected virtual string KeyTagName
{
get
{
return DEFAULT_KEY_TAG;
}
}
/// <summary>
/// Gets the XML tag name for a value.
/// </summary>
protected virtual string ValueTagName
{
get
{
return DEFAULT_VALUE_TAG;
}
}
#endregion
#region Public Methods
/// <summary>
/// Gets the XML schema for the XML serialization.
/// </summary>
/// <returns>An XML schema for the serialized object.</returns>
public XmlSchema GetSchema()
{
return null;
}
/// <summary>
/// Deserializes the object from XML.
/// </summary>
/// <param name="reader">The XML representation of the object.</param>
public void ReadXml(XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
{
return;
}
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.ReadStartElement(ItemTagName);
reader.ReadStartElement(KeyTagName);
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement(ValueTagName);
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
/// <summary>
/// Serializes this instance to XML.
/// </summary>
/// <param name="writer">The writer to serialize to.</param>
public void WriteXml(XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement(ItemTagName);
writer.WriteStartElement(KeyTagName);
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement(ValueTagName);
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
#endregion
}
You will find the reason why KeyValuePairs cannot be serialised at this MSDN Blog Post
The Struct answer is the simplest solution, however not the only solution. A "better" solution is to write a Custom KeyValurPair class which is Serializable.
[Serializable]
public class SerializableKeyValuePair<TKey, TValue>
{
public SerializableKeyValuePair()
{
}
public SerializableKeyValuePair(TKey key, TValue value)
{
Key = key;
Value = value;
}
public TKey Key { get; set; }
public TValue Value { get; set; }
}
In the 4.0 Framework, there is also the addition of the Tuple family of classes that are serializable and equatable. You can use Tuple.Create(a, b) or new Tuple<T1, T2>(a, b).
A KeyedCollection is a type of dictionary that can be directly serialized to xml without any nonsense. The only issue is that you have to access values by: coll["key"].Value;
XmlSerializer doesn't work with Dictionaries. Oh, and it has problems with KeyValuePairs too
http://www.codeproject.com/Tips/314447/XmlSerializer-doesnt-work-with-Dictionaries-Oh-and
Use the DataContractSerializer since it can handle the Key Value Pair.
public static string GetXMLStringFromDataContract(object contractEntity)
{
using (System.IO.MemoryStream writer = new System.IO.MemoryStream())
{
var dataContractSerializer = new DataContractSerializer(contractEntity.GetType());
dataContractSerializer.WriteObject(writer, contractEntity);
writer.Position = 0;
var streamReader = new System.IO.StreamReader(writer);
return streamReader.ReadToEnd();
}
}
DataTable is my favorite collection for (solely) wrapping data to be serialized to JSON, since it's easy to expand without the need for an extra struct & acts like a serializable replacement for Tuple<>[]
Maybe not the cleanest way, but I prefer to include & use it directly in the classes (which shall be serialized), instead of declaring a new struct
class AnyClassToBeSerialized
{
public DataTable KeyValuePairs { get; }
public AnyClassToBeSerialized
{
KeyValuePairs = new DataTable();
KeyValuePairs.Columns.Add("Key", typeof(string));
KeyValuePairs.Columns.Add("Value", typeof(string));
}
public void AddEntry(string key, string value)
{
DataRow row = KeyValuePairs.NewRow();
row["Key"] = key; // "Key" & "Value" used only for example
row["Value"] = value;
KeyValuePairs.Rows.Add(row);
}
}
You can use Tuple<string,object>
see this for more details on Tuple usage : Working with Tuple in C# 4.0

Categories

Resources