Can I convert from a JSON object graph to a .NET class without an intermediate string conversion?
My C# application receives JSON data which needs to be deserialized to strongly-typed objects, but I need to manipulate the JSON properties during conversion. Ideally I would like to deserialise to a JSON object graph, manipulate properties, and then convert the resulting graph to the .NET type. However, there seems to be no way of doing this except by serializing the modified graph back to a string, and then deserialize that string to the .NET type, which seems wasteful.
An example might explain why this is useful. The Twitter API sends lists of ids in the following form:
{"ids": [1, 2, 3], "next_cursor": 0, "previous_cursor": 0}
It sends lists of lists in a very similar form:
{"lists": [...], "next_cursor": 0, "previous_cursor": 0}
The obvious .NET equivalent of this is a CursorList<T> type with NextCursor, PreviousCursor and Contents properties, where Contents is IEnumerable<T> and contains the deserialized contents of the array. However, the standard JSON deserializers cannot deserialize to CursorList<T> because the JSON tag varies depending on T. I would like to take that JSON, deserialize to the object graph, extract the type-dependent property (ids or lists as the case may be), and hand it to the standard List<T> deserialization proces开发者_StackOverflow社区s. Having gone to all the trouble of creating an object graph, it seeems a shame to have to serialize that property to a JSON string before then redeserializing to List<T>.
I have looked at JSON.NET, System.Json and System.Web.ScriptSerialization.JavaScriptSerializer, but none of them seem to allow conversion between the JSON object graph and a .NET type. Does anyone have a way of doing this, or do I have to go via strings?
What is the source of your data?
There is no standard format for serializing POJOs to JSON. JSON representation of a Java POJO would be different from the one generated by Ruby.
Thus you have no choice other than handling it manually.
精彩评论