Deserialize JSON with JavaScriptSerializer

15,351

Solution 1

Here it seems like you've got an array of nodes and each node has a set of strings or another array of nodes, right? The first thing you could do is just deserialize this to a List<object> like so:

string treeData = "..."; // The JSON data from the POST
JavaScriptSerializer js = new JavaScriptSerializer();
List<object> tree = js.Deserialize <List<object>>(treeData);

This will turn your JSON into a list of objects, though you'll need to manually figure out what is what (if each object a string or another List<object>).

Generally, though, it helps to have some kind of class or struct to represent the "schema" for the the data you are giving the serializer, but it's a bit more work than the above.

In this instance, you'd need your input data to be an actual JSON object rather than just an array. Say you have this JSON (based on the above data):

{id: "root", children: [
  {id: "881150024"},
  {id: "881150024", children: [
    {id: "994441819"}, {id: "881150024"}]},
    {id: "-256163399"},
    {id: "-256163399", children: [            
    {id: "-492694206"},
      {id: "-256163399", children: [
        {id: "1706814966"},
        {id: "-256163399", children: [
          {id: "-26481618"}, {id: "-256163399"}]}
]}]}]}

If you have a class like this:

public class Node
{
  public String id;
  public List<Node> children;
}

You can then do something like:

string treeData = "..."; // The JSON data from the POST
JavaScriptSerializer js = new JavaScriptSerializer();
Node root = js.Deserialize<Node>(treeData);

That will be much easier to work with in code.

Solution 2

Taking into account answer by @_rusty.

In MVC3 it is possible to bing JSON data into actions, so your controller code would be very simple

[HttpPost]
public void SerializeTree(IList<Node> tree)
{
    // tree is deserialized JSON here
}

Solution 3

For those rare few of us still using VB.Net here and there:

Imports System.Web.Script.Serialization

'wsvcResponse<string> contains the following JSON object: { "foo":"bar", "foo2": { "bar2": "foobar" } }
Dim jsSerializer As New JavaScriptSerializer()
Dim jsonObject As List(Of Object) = jsSerializer.Deserialize(Of Object)(wsvcResponse)
Dim foo As String = jsonObject("foo").ToString  ' "bar"
Dim bar2 As String = jsonObject("foo2")("bar2").ToString ' "foobar"
Share:
15,351
podeig
Author by

podeig

Updated on June 13, 2022

Comments

  • podeig
    podeig almost 2 years

    I build a navigation tree and save the structure using this function in an array

    function parseTree(html) {
       var nodes = [];
       html.parent().children("div").each(function () {
          var subtree = $(this).children("div");
          var item = $(this).find(">span");
          if (subtree.size() > 0)
              nodes.push([item.attr("data-pId"), item.attr("data-id"), parseTree(subtree)]);
          else
              nodes.push(item.attr("data-pId"), item.attr("data-id"));
      });
      return nodes;
    }
    

    Then I serialize the data

    var tree = $.toJSON(parseTree($("#MyTree").children("div")));
    

    Get this array

    [
        ["881150024","881150024",
            [
             "994441819","881150024",
             "214494418","881150024"
            ]
        ],
        ["-256163399","-256163399",
            [
                "977082012","-256163399",
                "-492694206","-256163399",
                [
                    "1706814966","-256163399",
                        ["-26481618","-256163399"]
                ]
            ]
        ]
    ]
    

    And send it by ajax

                 $.ajax({
                    url: "Editor/SerializeTree",
                    type: "POST",
                    data: { tree: tree },
                    success: function (result) {
                        alert("OK");
                    }
                });
    

    Question: How do I Deserialize this JSON with JavaScriptSerializer in C#?

  • podeig
    podeig almost 13 years
    Well described! I used the second solution. I just needed to fix this line List<Node> root = js.Deserialize<List<Node>>(tree); Thank a lot. It was my first script with deserialization :-)
  • podeig
    podeig almost 13 years
    Thanks Alexander! I use MVC2 right now. When I update it to 3th version I will try this beautiful solution. :-)
  • Alexander Beletsky
    Alexander Beletsky almost 13 years
    @podeig, I would not wait :) and use MvcFutures to get required solution. It is very simple and beautiful, check this haacked.com/archive/2010/04/15/…
  • DeeKayy90
    DeeKayy90 about 10 years
    Really newbie question - in the Dim jsonObject As List(Of Object), do I replace Object with a Class I've created, or just leave it as Object?
  • rainabba
    rainabba about 10 years
    I'm using the generic Object class (which is rare for me as I generally use explicit types) mainly because I couldn't find a better way to get the results of the Deserialize() method casted. My initial instinct was : ".Deserialize(Of List(of string))(wsvcResposne) but I couldn't get that working as expected.