开发者

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


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.


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
}


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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜