开发者

Dynamic type selection by inspection of incoming JSON in WCF?

开发者 https://www.devze.com 2023-03-01 01:15 出处:网络
I have a complex heirarchy of JSON objects posting to a WCF service. By design and other requirements, each JSON object has an integer id representing conceptually its type or field layout (let\'s cal

I have a complex heirarchy of JSON objects posting to a WCF service. By design and other requirements, each JSON object has an integer id representing conceptually its type or field layout (let's call this the type id).

What I would like to accomplish is control over which .NET type is chosen for each JSON object's deserialization, through the inspection of each incoming integer type id.

Example input:

{
 "typeId": 4,
 "someField1": "foo",
 "someField2": "bar",
 "otherObject": 
    {
     "typeId": 7
     "someField3": "abc",
 开发者_JAVA百科    "someField4": "xyz"
    }
}

Example (Ideal) Process:

1. I receive partially parsed object.
2. I inspect "typeId" which has value 4.
3. I notify the deserialization process that I elect to use my .NET type FooBarA.
4. I receive partially parsed object.
5. I inspect "typeId" which has value 7.
6. I notify the deserialization process that I elect to use my .NET type FooBarB.

Is this or similar possible to do? I seem to recall asmx-style services used to include a __type field similar to my type id I suppose, but I don't recall its exact purpose or whether that can be enabled in WCF as an alternative perhaps.


You can collect the incoming JSON as a either a string (if you want the "concrete" type) or you can accept the JSON as a Stream (very useful if you are in a REST based scenario) and then copy it into a MemoryStream for processing several times over. Since the DataContractJsonSerializer works off the Stream, your best use case is dumping it into the MemoryStream.

The deserialization use case you are describing is going to be rather difficult to pull off because if the nested object (in your case "otherObject") is not a member of the parent class (in this case FooBarA) then the deserialization process is just going to ignore the value because it has nowhere to put it.

Switching gears, a more time consuming process would use Json.Net and you could step through the JSON in a similar style as you would with Linq to XML. The advantage of Json.Net is that it allows you to play with JSON that doesn't necessarily map perfectly to concrete classes. It doesn't play nicely with WCF in the serialization chain, but I've used it a few times on the WCF side to deal with JSON that gets supplied that doesn't match up exactly with what an concrete class is looking for.

You can find Json.Net here - http://json.codeplex.com/

0

精彩评论

暂无评论...
验证码 换一张
取 消