Skip to main content

Microsoft Silverlight

Answered Question How to convert System.JSON CLR to .NET CLR in C# (Silverlight)RSS Feed

(0)

cliffkoh
cliffkoh

Member

Member

0 points

2 Posts

How to convert System.JSON CLR to .NET CLR in C# (Silverlight)

Hi,

In Silverlight, there is the System.Json namespace which provides a feel classes to deal with parsing (and encoding) JSON.

I am however, facing a problem now converting the JSON CLR types such as System.Json.JsonType.String (which is actually a System.Json.JsonPrimitive object with type String) into the .NET equivalent (the string primitive).

E.g.

Json:

{"Hello": "World"}

C#

JsonValue temp = JsonValue.Parse(jsonCodeFromAbove);

What I want to do is to retrieve the string in temp["Hello"]. temp["Hello"] by itself returns a JsonValue and not a string however, and temp["Hello"].ToString() returns

"\"World\""

which is actually expected behaviour by the documentation (serialises it back into Json).

How do I get the string value without the quotes? (i.e. string value = ...somecodehere...)

Jonathan Shen – MSFT
Jonathan...

All-Star

All-Star

24939 points

2,425 Posts

Microsoft

Re: How to convert System.JSON CLR to .NET CLR in C# (Silverlight)

Hi Cliffkoh,

To get the Json object on Silverlight 2, we need to first get the returned JSON string.  Then, use DataContractJsonSerializer to convert it.  Below is a working sample. 

<!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" >
<!-- saved from url=(0014)about:internet -->
<head>
    <title>Silverlight Project Test Page </title>

    <style type="text/css">
    html, body {
	    height: 100%;
	    overflow: auto;
    }
    body {
	    padding: 0;
	    margin: 0;
    }
    #silverlightControlHost {
	    height: 300px;
    }
    </style>
    <script type="text/javascript" src="prototype.js"></script>
    <script type="text/javascript">
        var Person = {
           "firstName": "John",
           "lastName": "Smith",
           "address": {
               "streetAddress": "21 2nd Street",
               "city": "New York",
               "state": "NY",
               "postalCode": 10021
           }
         };
         
        function sendJSON(){ document.getElementById("SL").Content.Bridge.SendJSON(Object.toJSON(Person)); }
         
        function onSilverlightError(sender, args) {
            if (args.errorType == "InitializeError")  {
                var errorDiv = document.getElementById("errorLocation");
                if (errorDiv != null)
                    errorDiv.innerHTML = args.errorType + "- " + args.errorMessage;
            }
        }
    </script>
   </head>

<body>
    <!-- Runtime errors from Silverlight will be displayed here.
	This will contain debugging information and should be removed or hidden when debugging is completed -->
	<div id='errorLocation' style="font-size: small;color: Gray;"></div>

    <div id="silverlightControlHost">
		<object data="data:application/x-silverlight," type="application/x-silverlight-2" width="500px" height="300px" id="SL">
			<param name="source" value="ClientBin/JsonToSilverlight.xap"/>
			<param name="onerror" value="onSilverlightError" />
			<param name="background" value="white" />
			
			<a href="http://go.microsoft.com/fwlink/?LinkID=108182" style="text-decoration: none;">
     			<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
			</a>
		</object>
		<iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe>
    </div>
        
    <input type="button" value="send JSON to SL" onclick="sendJSON()" id="btnSendJSON" />
</body>
</html>
  Page.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using System.Runtime.Serialization;
using System.ServiceModel;

namespace JsonToSilverlight
{
    public partial class Page : UserControl
    {
        public Page(){
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Page_Loaded);
        }

        void Page_Loaded(object sender, RoutedEventArgs e)
        {
            HtmlPage.RegisterScriptableObject("Bridge", this);
        }

        [ScriptableMember]
        public void SendJSON(string json)
        {
            Person p = new Person();
            System.Runtime.Serialization.Json.DataContractJsonSerializer jsSer = 
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Person));
            System.IO.MemoryStream ms = new System.IO.MemoryStream(Encoding.Unicode.GetBytes(json));
            p = jsSer.ReadObject(ms) as Person;
            ms.Close();

            //Display object in UI
            stackDebugText.Children.Clear();
            stackDebugText.Children.Add(Text("Person object"));
            stackDebugText.Children.Add(Text("firstName: " + p.firstName));
            stackDebugText.Children.Add(Text("lastName:" + p.lastName));
            stackDebugText.Children.Add(Text("Address"));
            stackDebugText.Children.Add(Text("streetAddress: " + p.address.streetAddress));
            stackDebugText.Children.Add(Text("state:" + p.address.state));
            stackDebugText.Children.Add(Text("city: " + p.address.city));
            stackDebugText.Children.Add(Text("postalCode:" + p.address.postalCode.ToString()));

        }

        private TextBlock Text(string txt)
        {
            TextBlock t = new TextBlock();
            t.Text = txt;
            return t;
        }
    }
}

You can download the sample here.  Note:  This sample is written by Silverlight 2 beta.  Thus, after we convert it to Silverlight 2, we need to go to index.html and change its type to  type="application/x-silverlight-2".   Also, you'd better take a look at this article. 

Best regards,

Jonathan

Jonathan Shen
Microsoft Online Community Support
Please remember to mark the replies as answers if they help and unmark them if they provide no help.

cliffkoh
cliffkoh

Member

Member

0 points

2 Posts

Answered Question

Re: Re: How to convert System.JSON CLR to .NET CLR in C# (Silverlight)

There is a System.JSON namespace (though one would need to manually add a reference to it in Visual Studio) where it is actually very much easier to interact with JSON.

I initially attempted to use extension methods to get around the initial problem above, then subsequently someone pointed out to me that in spite of what you see in the Debugger, you can get the string values directly (if it was a JsonPrimitive with JsonType.String) by just using

 string temp = json["path"];

 directly without having to use the .ToString() method.

  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities