Postsharp and Json.NET - json.net

I'm new to PostSharp and trying to do something that that has me vexed, but seems simple:
I'm trying to use Json.Net to serialize and deserialize an instance of MethodInterceptionArgs
Serialization work fine:
string strArgs = JsonConvert.SerializeObject(args);
But I seem to be missing something when deserializing it: What class should I be deserializing it to? MethodInterceptionArgs is abstract, so I don't think that will work.
I could create my own concrete implementation, but that seems ilke it shouldn't be necessary (and I keep getting an error that MethodInterceptionArgs does not contain a constructor that takes zero arguments)

MethodInterceptionArgs is not meant to be serialized. You should copy the relevant pieces of information into another object and serialize it.

Related

JSON.net ContractResolver vs. JsonConverter

I've been working with JSON.net for a while. I have written both custom converters and custom contract resolvers (generally from modifying examples on S.O. and the Newtonsoft website), and they work fine.
The challenge is, other than examples, I see little explanation as to when I should use one or the other (or both) for processing. Through my own experience, I've basically determined that contract resolvers are simpler, so if I can do what I need with them, I go that way; otherwise, I use custom JsonConverters. But, I further know both are sometimes used together, so the concepts get further opaque.
Questions:
Is there a source that distinguishes when to user one vs. the other? I find the Newtonsoft documentation unclear as to how the two are differentiated or when to use one or the other.
What is the pipeline of ordering between the two?
Great question. I haven't seen a clear piece of documentation that says when you should prefer to write a custom ContractResolver or a custom JsonConverter to solve a particular type of problem. They really do different things, but there is some overlap between what kinds of problems can be solved by each. I've written a fair number of each while answering questions on StackOverflow, so the picture has become a little more clear to me over time. Below is my take on it.
ContractResolver
A contract resolver is always used by Json.Net, and governs serialization / deserialization behavior at a broad level. If there is not a custom resolver provided in the settings, then the DefaultContractResolver is used. The resolver is responsible for determining:
what contract each type has (i.e. is it a primitive, array/list, dictionary, dynamic, JObject, plain old object, etc.);
what properties are on the type (if any) and what are their names, types and accessibility;
what attributes have been applied (e.g. [JsonProperty], [JsonIgnore], [JsonConverter], etc.), and
how those attributes should affect the (de)serialization of each property (or class).
Generally speaking, if you want to customize some aspect of serialization or deserialization across a wide range of classes, you will probably need to use a ContractResolver to do it. Here are some examples of things you can customize using a ContractResolver:
Change the contract used for a type
Serialize all Dictionaries as an Array of Key/Value Pairs
Serialize ListItems as a regular object instead of string
Change the casing of property names when serializing
Use camel case for all property names
Camel case all property names except dictionaries
Programmatically apply attributes to properties without having to modify the classes (particularly useful if you don't control the source of said classes)
Globally use a JsonConverter on a class without the attribute
Remap properties to different names defined at runtime
Allow deserializing to public properties with non-public setters
Programmatically unapply (ignore) attributes that are applied to certain classes
Optionally turn off the JsonIgnore attribute at runtime
Make properties which are marked as required (for SOAP) not required for JSON
Conditionally serialize properties
Ignore read-only properties across all classes
Skip serializing properties that throw exceptions
Introduce custom attributes and apply some custom behavior based on those attributes
Encrypt specially marked string properties in any class
Selectively escape HTML in strings during deserialization
JsonConverter
In contrast to a ContractResolver, the focus of a JsonConverter is more narrow: it is really intended to handle serialization or deserialization for a single type or a small subset of related types. Also, it works at a lower level than a resolver does. When a converter is given responsibility for a type, it has complete control over how the JSON is read or written for that type: it directly uses JsonReader and JsonWriter classes to do its job. In other words, it can change the shape of the JSON for that type. At the same time, a converter is decoupled from the "big picture" and does not have access to contextual information such as the parent of the object being (de)serialized or the property attributes that were used with it. Here are some examples of problems you can solve with a JsonConverter:
Handle object instantiation issues on deserialization
Deserialize to an interface, using information in the JSON to decide which concrete class to instantiate
Deserialize JSON that is sometimes a single object and sometimes an array of objects
Deserialize JSON that can either be an array or a nested array
Skip unwanted items when deserializing from an array of mixed types
Deserialize to an object that lacks a default constructor
Change how values are formatted or interpretted
Serialize decimal values as localized strings
Convert decimal.MinValue to an empty string and back (for use with a legacy system)
Serialize dates with multiple different formats
Ignore UTC offsets when deserializing dates
Make Json.Net call ToString() when serializing a type
Translate between differing JSON and object structures
Deserialize a nested array of mixed values into a list of items
Deserialize an array of objects with varying names
Serialize/deserialize a custom dictionary with complex keys
Serialize a custom IEnumerable collection as a dictionary
Flatten a nested JSON structure into a simpler object structure
Expand a simple object structure into a more complicated JSON structure
Serialize a list of objects as a list of IDs only
Deserialize a JSON list of objects containing GUIDs to a list of GUIDs
Work around issues (de)serializing specific .NET types
Serializing System.Net.IPAddress throws an exception
Problems deserializing Microsoft.Xna.Framework.Rectangle

How to deserealize undefined and nested Hashtable structure with json.net

How to deserealize undefined and nested Hashtable structure with json.net?
for example:
#"{"a" : {"b" : 1}}"
Hashtable data = JsonConvert.DeserializeObject<Hashtable>(json_str)
returns Newtonsoft.Json.Linq.JObject at data["a"], instead Hashtable
If the structure of the JSON is not known ahead of time, and the JSON does not contain any type metadata to help Json.Net figure things out, then Json.Net has no choice but to use JTokens (JObject, JProperty, JArray, JValue, etc.) to deserialize things into. That is how it is designed to work.
If you prefer to work with Hashtables, it should be possible to convert the JToken object graph into a nested Hashtable structure after the deserialization, but I'm not sure you gain much by doing that. You would be better off just learning how to read the data out of the JTokens directly. (You would have to do so in order to do the conversion anyway.)

Json.net deserialization of data type ConcurrentBag

I have an object with a property of type ConcurrentBag<object>.
When I am trying to deserialize a json string to my object using JsonConvert.DeserializeObject(), I get an exception which indicates the serializer is failing to convert from an array to the object's ConcurrentBag<object> data type.
Any help to solve this problem would be appreciated.
I think you will have to write a converter of sorts. Kinda like this post:
json.net: specify converter for dictionary keys
This website also has some more examples:
http://weblogs.asp.net/thangchung/archive/2010/08/26/customizing-the-converter-for-json-net.aspx

NHibernate.IFutureValue<> when serialized includes .Value

I'm building an ASP.NET (2.0, no, I can't change it) site with NHibernate, and have a custom JSON converter so I can not-serialize properties I want hidden from the client. This lets me just return the objects, and never have to worry about their serialized values - they're always secure.
Unfortunately, it appears that if I use query.FutureValue<class>(), the object that gets serialized is first the NHibernate.Impl.FutureValue<class> and not my entity, which means I get JSON that looks like this if I throw it in a dictionary and return it to the client:
{key: { Value: { /* my serialized object properties */ } }
Previously I discovered that I can't get any interfaces to work in ASP's JavaScriptConverter implementations... only regular or abstract classes. So returning typeof(IFutureValue<MyBaseClass>) as a supported type means my converter is completely ignored. I can catch MyBaseClass, because I refactored things earlier to use an abstract base instead of an interface, but not the interface.
And then I discover that the FutureValue implementation in .Impl is internal to the assembly, or some other such nonsense that only serves to make my .NET experience even more painful. So I can't use typeof(FutureValue<MyBaseClass>) to handle it all, because FutureValue exists only in my debugging sessions.
Is there a way to get the class type out of the assembly? Or a way to convince ASP that interfaces do in fact have uses? Or might there be some superclass I can access that would let me get around the whole issue?
Help! I like my Futures, it lets me batch a whole heck-ton of calls at once!
(if something isn't clear, or you want more code, by all means, ask! I can post quite a bit.)
If I'm understanding you correctly, it seems you are mixing things a together a little bit.
It sounds like you're trying to serialize an instance of query.FutureValue<class>(), which unsurprisingly gives you just that: a JSON object where the Value fields has JSON representing your entity.
To me it sounds like you really want to just serialize query.FutureValue<class>().Value.
Using NHibernate futures like this gives you little benefit though, so you're probably after something like:
var future1 = query1.FutureValue<SomeEntity>();
var future2 = query2.FutureValue<AnotherEntity>();
var json1 = serializer.Serialize(future1.Value); //<BAM! Multi-query gets fired!
var json2 = serializer.Serialize(future2.Value);
Does that make sense?

How to determine which classes are serializable

I am changing my ASP.NET app to use a web farm. To do this, I need to change the session state from in-proc to a State Server. To do this, it is my understanding that the classes that are used must be marked as serializable. How can you tell if that is possible with a class? Will you get an error at compile time if it is not possible?
In answer to your first question about how to tell whether or not a class is serializable, see the following discussion. How to check if an object is serializable in C#
Unfortunately, .net has surprised me with bizarre behavior when I try to serialize objects that I think should be serializable.
For example, in my WCF projects, I can serialize and transmit DataSet objects. However, if I try to serialize and transmit DataTable objects, I end up with a blank DataTable. It took me a while to track that one down.
Therefore, I would suggest that you do at least some rudimentary testing of what happens when you try to serialize custom classes.
You won't get a compile-time exception, since compile-time doesn't really know whether the objects will need to be serialized. You'll get a SerializationException when IIS attempts to serialize your objects.
You can write a short snippet that attempts to serialize and de-serialize the objects in question... use a BinaryFormatter to do the serialization, and a FileStream to write to.
The ObjectBrowser will tell you if an existing class implements ISerializable. If you're looking at your own objects to serialize, keep in mind that classes must really be designed for serialization if they are intended to be serialized, otherwise there are gotchas. For example, from the MSDN help:
The order in which objects are deserialized cannot be guaranteed. For example, if one type references a type that has not been deserialized yet, an exception will occur.
I recommend reading up in ISerializable... here's a link: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx
EDIT: Here is a simple example of serialization and deserialization... just replace the Exception I'm serializing with your own objects:
BinaryFormatter formatter = new BinaryFormatter();
Exception serializedException = new Exception("Testing serialization");
Exception deserializedException;
using (FileStream fileStream = new FileStream(#"C:\SerializationTest.txt", FileMode.CreateNew)) {
formatter.Serialize(fileStream, serializedException);
}
using (FileStream readStream = new FileStream(#"C:\SerializationTest.txt", FileMode.Open)) {
deserializedException = formatter.Deserialize(readStream) as Exception;
}
if (deserializedException != null) {
throw deserializedException;
}

Resources