Web Services – JSON – Strongly Typed Classes



Years ago I was introduced to Web Services and immediately found it to be a critically needed component of a total business solution. With Web Services I could now completely break the relationship that usually exists between an end-user application and a data store.

For years I have implemented solutions with web services as a middle layer. These services have been SOAP based and provided XML output. For solutions that use a web service which exist on the same box or in a closed network the XML payload does not typically produce a performance problem.

Recently I have been introduced to a newer technology that will reduce the payload over the wire. At the same time we are building a solution where the clients calling the web service will reside anywhere in the world. With a different user base model it is time to explore options other than XML.

In comes JSON, a compact style of describing data. The way JSON describes data the payload over the wire is greatly reduced.

Now – implementation! What do I need to do differently in my service to output JSON and to accept JSON?

Additionally, can I use my current programming style of creating strongly typed classes and leaning on collections over arrays and still output and accept JSON strings?

The following walkthrough is designed to demonstrate the answers to these questions.

It is expected that you have created at least one Web Service solution with Visual Studio. I am using VS2008 in this example. The simplified solution represents a Parts Store that wishes to expose and accept Parts information as JSON data streams.

1) Create a new Web Service. I named mine – JSONService.

2) Next I do what I would do with a SOAP based service.

a. Create a class named ‘Store’.

[pic]

b. Create a classes named ‘Part’ and ‘Parts’.

[pic][pic]

c. Create a Web Method to return a Store and its Parts.

[pic]

In a production situation the actual data would come from a database. For this example I create a simple function that builds a fictitious store with 3 parts.

d. Test the Web Service and the 1st Method.

[pic]

This is a typical SOAP output.

3) Now let’s push the same data out as a JSON data stream.

a. Create a new Web Method.

[pic]

The built-in .NET serialization objects will produce a JSON String from a typed object. Invoke the Serialize method from the JavaScriptSerializer, passing in the typed object.

b. Review the output.

[pic]

Clearly, the number of characters produced is substantially less than the SOAP XML output. It does not require more than comparing these two outputs to determine that a JSON data stream will be more efficient will traveling over the wire.

However, I see that the JSON string is encapsulated inside xml tags. This makes the output just a simplified xml document and not a true JSON string. Lets remove the xml tags.

4) Remove xml wrapper from the JSON string.

a. Create a new Method to limit the output to the JSON string.

[pic]

Take note that this is a Sub and not a Function! A reference is created to the current HttpContext which gives us direct access to the Response stream going back to the client. The last line writes the JSON string directly to the Response stream. This causes the code that would have wrapped the output inside an xml element to be completely bypassed.

b. Review the results.

[pic]

Now the output is as clean as it gets!

5) Last challenge – Accept a JSON string and convert to a typed object.

If you review the Serialization documentation you will see that not all types can be DeSerialized from a JSON string.

If you only handle simple types (strings, integers, dates, etc) then converting a JSON string back to a typed object is not complex. But, of course, I never do anything that is simple!

I first built code, using samples from MSDN and other sites, to DeSerialize the JSON string and it kept failing. After trial and error to identify exactly where it was failing I found that it was not correctly pushing the data back into my collections.

So, I asked myself, why is this not working? The data is there! Why can’t it recognize the relationship between the name value pairs in the string and the properties of my object.

Then the light bulb turned on! The JSON string is representing the items in the collection as a simple array. I am trying to push an array into a collection – NOT Going to HAPPEN!

So, what now? OKAY – here are my thoughts. Do I need the JSON to be represented as a collection to work with it in server code? Not necessarily! Do I absolutely need the JSON string to be pushed back into the exact object I used to create the string? Not necessarily! I just want it into a typed object. What is my purpose in pushing the string back into a typed object? Answer: To facilitate the ease of evaluating the data in code and taking necessary action. i.e. Save to database, evaluate and respond with a new output string, etc. Will I need to modify the data? (Add or Remove array items?) No! When it comes back into the server it will not likely require ‘Acting Upon’ but ‘Acting With’.

Conclusion – Create companion classes that will be the target of the passed in JSON string.

a. Create simple classes that mirror the more complex classes.

[pic][pic]

Note that the Parts collection has become a Parts array. Also note that there is NO PartsJSON class.

b. Create a new Web Method (or if you are me, create your 50th variation!).

[pic]

The key here is the DataContractJsonSerializer. By passing in my StoreJSON class then when it performs the Serialization it attempts to match the data with the structure of the typed object.

c. Test the method.

[pic]

I took the output from _3Store_Json web method and pasted it directly into the value textbox.

[pic]

There you have it! All the same data and data structure except for the external wrapper!

Richard Hancock

Vega Discoveries



-----------------------

Figure 1 - VS Explorer

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download