Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON with JavaScriptSerializer

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#?

like image 519
podeig Avatar asked Dec 16 '22 14:12

podeig


2 Answers

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.

like image 115
rusty Avatar answered Jan 01 '23 02:01

rusty


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
}
like image 26
Alexander Beletsky Avatar answered Jan 01 '23 02:01

Alexander Beletsky