Question

NET 2.0 client - deserialize JSON obj

Asked by: nespa

if i have a plain-ol .net 2.0 proxy (client for rest-service) and that rest service returns JSON output, what's my best option to DESERIALIZE the json output back into an object?

said in ol-school church lady voice:
is it... AJAX.NET 2.0 Extensions 1.0...maybe?????!!!!

i don't want to have to load that entire library...or should i just parse it out myself?

or should i just load the damn library already (for my measly .net 2.0 client).

help me lord.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-28 at 08:53:00ID24690205
Tags

JSON

,

NET 2.0

,

deserialization

Topics

JSON

,

.NET Framework 2.x

Participating Experts
1
Points
500
Comments
12

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. SNES - Lord Of The Rings
    Super Nintendo - Lord Of the Rings I have completed the final caves and killed the flying monster, only to find that I must have forgot to do something. I would like to know the exact sequence of events. When I get to the end, I get a rolling screen and then the game lock...
  2. Prototype and JSON (or XML).
    Hi all, Firstly, I'm new to prototype, & am trying to use the version 1.5.0_rc1. I'm trying to get prototype to dynamically read JSON formatted data & display it in a textbox. I got the URL from http://developer.yahoo.com/common/json.html but I'm not sure I'm formatt...
  3. Is the quality of COMCAST Digital Voice up-to-par for a B…
    We are considering to the Comcast Digital Voice for our 5 Business phone lines. We've had issues with are telephone line form the local phone company. Is Comcast Business Phone Service a good quality service? I'm looking for people who have use this system. We will be c...
  4. JSON Deserialization in asp.net VB
    I can not seem to get json deserialization to work correctly in asp.net vb the problem seems to be in the type casting. The JSON string represents an array of (skill_ser) which itself contains several arrays of (skill_ser) Thank you for your help!
  5. Issues with Deserialize JSON in C#
    I have been trying to find a solution to a problem I'm running into and can't seem to figure it out. I have a application I'm writing to convert from one software to a new one. Well because doing the setup and conversion can take some time, I decided to writing in a option to...
  6. Sys.ArgumentException: Cannot deserialize. The data d…
    I'm having trouble with one of my user controls when it is placed in an UpdatePanel. The control is a database bound GridView with a custom filter area above it. In the filter area, the user can select a column to filter on and enter the value to look for. There is a filter p...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: nespaPosted on 2009-08-28 at 08:55:57ID: 25208951

...and i won't be lazy about this...i'll download the source for the library right now...while yer having your starbucks trying to decide if you should bother to answer this.

can i just steal it & put in my code or do i have to sign in blood to microsoft that they are the ultimate?

why is there air?

i'll report back shortly... thanks.

 

by: nespaPosted on 2009-08-28 at 09:42:21ID: 25209404

why do i let people talk me into using microsoft libraries to do ajax-related stuff?   where's ruby when you need her?

have you had your starbucks?

 

by: ddayx10Posted on 2009-08-28 at 09:49:48ID: 25209485

I'm not sure exactly what you mean, but what the hay, if it's not helpful don't use it :)

When a JSON string is returned from a webservice, in many cases the result is automatically converted back into an object in JavaScript for example. I'm guessing you're talking about returning an object from a webservice in JSON format and then retaining the object structure as you use it in JavaScript? Not sure though you could be using the service in code behind?

Of course the object must be serializable, so if you're making the webservice yourself you have to bone up on that aspect. Most custom objects are or can be made serializable, but it can get tricky, usually its pretty academic (it just works).

So here's an example of a page that calls a webservice. The webservice creates a custom object and returns that as a JSON serialized string to the page. Then I use the OO structure on the returned object to populate it on the page...hope its of some help to you.

*****ASPX PAGE****
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>JSON Object</title>
    <script type="text/javascript">
		
		function hello()
		{
			var name = $get('inName').value;
			var age = parseInt($get('inAge').value);
			WebService.HelloWorld(name, age, rMethod);
		}
		
		function rMethod(rValue)
		{
			$get('results').innerHTML = rValue.a + ' ' + rValue.b;
		}
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server">
		<Services>
			<asp:ServiceReference Path="WebService.asmx" />
		</Services>
    </asp:ScriptManager>
		
		<div>
		<span>Name:</span>
		<input id="inName" type="text" />
		</div>
		
		<div>
		<span>Age:</span>
		<input id="inAge" type="text" />
		</div>
 
		<input type="button" value="Make JSON" onclick="hello();return false;" />
		
		<div id="results"></div>
		
    </form>
</body>
</html>
 
 
****WEB SERVICE****
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
 
    public WebService () {}
 
    [WebMethod]
    public testObject HelloWorld(string name, int age) 
    {
        return new testObject(name,age);
    }
    
}
 
public class testObject
{
    public string a { get; set; }
    public int b { get; set; }
 
    public testObject(string a1, int b1)
    {
        a = a1;
        b = b1;
    }
    
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:

Select allOpen in new window

 

by: ddayx10Posted on 2009-08-28 at 09:50:36ID: 25209493

>>>why do i let people talk me into using microsoft libraries to do ajax-related stuff?  

Because they're super powerful once you get the hang of things :)

 

by: ddayx10Posted on 2009-08-28 at 10:06:33ID: 25209618

OR here's the same example with things a bit more manually done. In the WebService instead of returning an object type (which the framework handles for me) I am returning a JSON serialized string.

The return from the webservice method would look something like this (depending on what values are sent in):
{"a":"ddrfd","b":4}

This is returned to JavaScript and using the built in libraries I can manually convert it to an object. You can see how this is handled in the updated rMethod function.

****ASPX PAGE****
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>JSON Object</title>
    <script type="text/javascript">
		
		function hello()
		{
			var name = $get('inName').value;
			var age = parseInt($get('inAge').value);
			WebService.HelloWorld(name, age, rMethod);
		}
		
		function rMethod(rValue)
		{
			var oReserialized = Sys.Serialization.JavaScriptSerializer.deserialize(rValue);
			$get('results').innerHTML = oReserialized.a + ' ' + oReserialized.b;
		}
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server">
		<Services>
			<asp:ServiceReference Path="WebService.asmx" />
		</Services>
    </asp:ScriptManager>
		
		<div>
		<span>Name:</span>
		<input id="inName" type="text" />
		</div>
		
		<div>
		<span>Age:</span>
		<input id="inAge" type="text" />
		</div>
 
		<input type="button" value="Make JSON" onclick="hello();return false;" />
		
		<div id="results"></div>
		
    </form>
</body>
</html>
 
 
****WEBMETHOD****
 
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Web.Script.Serialization;
 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
 
    public WebService () {}
 
    [WebMethod]
    public string HelloWorld(string name, int age) 
    {
        testObject to = new testObject(name, age);
        JavaScriptSerializer json = new JavaScriptSerializer();
        string rValue = json.Serialize(to);
        //{"a":"ddrfd","b":4}
        return rValue;
    }
    
}
 
public class testObject
{
    public string a { get; set; }
    public int b { get; set; }
 
    public testObject(string a1, int b1)
    {
        a = a1;
        b = b1;
    }
    
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:

Select allOpen in new window

 

by: nespaPosted on 2009-08-28 at 13:01:37ID: 25211145

>>>why do i let people talk me into using microsoft libraries to do ajax-related stuff?  

>>Because they're super powerful once you get the hang of things :)

yes...but i meant vs. other ajax libraries.   :)   however i know that's a religious preference as there are tons of ajax frameworks & libraries out there (but a few solid main contenders).

 

by: nespaPosted on 2009-08-28 at 13:40:08ID: 25211387

ddayx10 - those are great examples; i do appreciate the time it took to pull them together as they are helpful (i.e. i know json parsed out in javascript is GENERALLY the way to go / generally how json is used in the field)   but i have something a little different (and it's my fault for not expressing this more appropriately...i wuz just frustrated w/ my options).

BACKGROUND:
- i'm returning data from a service; List<myObj>  ...serialized into a JSON string.

- MOST of my consumers of my 3.5 WCF REST-ful service want & use JSON in appropriate format (i.e. parse it out in javascript or bind to UI components using JQuery or AJAX /JS library approach).

so in these cases JSON is perfect, does its job...simple simple.

- i have ONE client for whom i'm to create a proxy obj. to call my RESTful service.   they expect a DLL to be able to be installed on a website & pass response back to them, which they can in turn feed the end client/browser.

- it would be AWESOME (oh be it) that they would be able to accept json as output (in a string) from my proxy object...but they are asking for an actual object instead (i have to deserialize the JSON string into a typed object)

so i either build in XML as response type for that one consumer & handle separately OR if i can convince them json would be a simpler way to go to display data coming from the service...then that might be a good thing.


RESULTS FROM MY TESTING:
- i was able to extract out and create a JavaScriptSerializer.Deserialize method using AJAX extensions 1 (the ol' school .NET 2.0 version)

this worked BUT i must insert the TYPE of the object to make that method work...so still tightly coupled (would have to change my service & proxy, should myObj change)

and my proxy must be 2.0 --- if i had 3.5 framework as an option i could use DataContractJsonSerializer.


in terms of answering my question, i guess JavaScriptSerializer.deserialize (part of ajax extensions) is the best approach for a .NET way of deserializing json into object format?   unless there are any other ideas?

thanks again for the input.

 

by: ddayx10Posted on 2009-08-31 at 10:16:23ID: 25224516

Sounds like you have a powerful understanding of this stuff already :)

Why is there always one who insists the world conforms to him? I mean JS/XML whatever you choose are used precisely to overcome these types of issues! To send them an object is going to require some intermediary... ah well they must be good consumers or you'd not be putting up with this I suppose.

Wish I had any suggestions for you. I think you're best bet is a sales job on your client in getting them to accept JSON or XML. I don't see how you can send an "object"?!

PS: the code samples I did were extremely basic and required very little effort, no worries :)

 

by: nespaPosted on 2009-09-23 at 03:43:32ID: 25401537

this one was tricky:  i needed to provide a SERIALIZE method on an object in a client-side proxy.   the object gets created by the proxy by making a call to a REST service.  and only .NET 2.0 available on the machine running the client-side proxy.

TWO ANSWERS i found to this solution:

1) as mentioned above I extracted out the necessary portion of JsonDeserialize from AJAX 2.0 Extensions 1.0...which deserialized JSON output from REST service *into* an object for my .net 2.0 class library to use to feed the object to my client (the client consumes the class library and I call the rest service to get them their object).

BUT - then tightly coupled with the client and it's not a very flexible design either, should my object change.  AND - i'm not sure microsoft is cool with me pulling out just the stuff i needed from their AJAX library...at least not without tons of disclaimers or something.

...and i have to have a shared class library with my MyServerObjType in it.

2) the solution i went with:  i added a web service interface (regular ol' WCF web service on server side), returned XML as output.  this gets automatically deserialized by the client-side proxy which of course gets auto-generated as you add a reference to your service (STEP 1)

then i found that attempting to include the ToXml and use [Serialize] inside the DataContract which I was returning would cause the compiler to choke...since that DataContract itself gets serialized & deserialized on the server side, with the ToXml method never showing up on the client after deserialization into an object.

(STEP 2 - workaround) i wound up putting a ToXml method inside a helper class alongside the client proxy...so now i can do HelperClass.GetXml(typeof(someObjReturnedFromMyWebService))...and it creates the Xml output for any clients that need to serialize my obj. returned by the client proxy.

this is more flexible as i don't have to use the json deserialization method from microsoft...and if my object changes server-side i just regenerate my serviceProxy...eliminating the need for a sharedLibrary which holds MyServerObjType in it, since that obj. is part of the serviceProxy.

thanks to ddayx10 for the responses...if i simply had the browser as my client (instead of a .NET class library as a proxy) i could've use dday's code which is a nice example of how to deserialize using javascript.  i had to deserialize using C#, as my class library is consumed by another C# object, not a browser.

hope the above makes sense...and maybe my explanation can be simplified...but it's early.  :)

 

by: nespaPosted on 2009-09-23 at 03:48:05ID: 25401581

please don't close this question...just added solution above if it helps someone.

 

by: nespaPosted on 2009-09-24 at 08:04:26ID: 25414091

hey, just realized; ok to close this question...i awarded some points to ddayx for the help and responses...

as long as closing means it's still available in the forum (but closed to responses) then that's perfect - thanks.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...