pod*_*eig 4 c# serialization json deserialization
我构建了一个导航树,并在数组中使用此函数保存结构
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;
}
Run Code Online (Sandbox Code Playgroud)
然后我序列化数据
var tree = $.toJSON(parseTree($("#MyTree").children("div")));
Run Code Online (Sandbox Code Playgroud)
获取此数组
[
["881150024","881150024",
[
"994441819","881150024",
"214494418","881150024"
]
],
["-256163399","-256163399",
[
"977082012","-256163399",
"-492694206","-256163399",
[
"1706814966","-256163399",
["-26481618","-256163399"]
]
]
]
]
Run Code Online (Sandbox Code Playgroud)
并通过ajax发送
$.ajax({
url: "Editor/SerializeTree",
type: "POST",
data: { tree: tree },
success: function (result) {
alert("OK");
}
});
Run Code Online (Sandbox Code Playgroud)
问题:如何在C#中使用JavaScriptSerializer反序列化此JSON?
rus*_*sty 11
在这里,你似乎有一个节点数组,每个节点都有一组字符串或另一个节点数组,对吧?你可以做的第一件事就是将其反序列化为List<object>如此:
string treeData = "..."; // The JSON data from the POST
JavaScriptSerializer js = new JavaScriptSerializer();
List<object> tree = js.Deserialize <List<object>>(treeData);
Run Code Online (Sandbox Code Playgroud)
这会将您的JSON转换为对象列表,但您需要手动确定是什么(如果每个对象都是字符串或其他对象List<object>).
但是,通常情况下,使用某种类或结构来表示您为序列化程序提供的数据的"模式"会有所帮助,但它比上面的工作要多一些.
在这种情况下,您需要输入数据是实际的JSON对象而不仅仅是数组.假设你有这个JSON(基于以上数据):
{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"}]}
]}]}]}
Run Code Online (Sandbox Code Playgroud)
如果您有这样的课程:
public class Node
{
public String id;
public List<Node> children;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
string treeData = "..."; // The JSON data from the POST
JavaScriptSerializer js = new JavaScriptSerializer();
Node root = js.Deserialize<Node>(treeData);
Run Code Online (Sandbox Code Playgroud)
这将更容易在代码中使用.