【发布时间】:2010-10-23 04:40:17
【问题描述】:
是否有一个库(首选 C#)来解决我称之为多级级联 JSON 的问题?
这是我的意思的一个例子:(伪代码/C#)
var json1 = @"{
""firstName"": ""John"",
""lastName"": ""Smith""
}";
var json2 = @"{
""firstName"": ""Albert""
}";
var json3 = @"{
""phone"": ""12345""
}";
var cascadingJSON = JSON.Cascade(json1, json2, json3);
结果(与 CSS 相同的行为)
{
"firstName"": "Albert", /*Overridden*/
"lastName"": "Smith", /*Inherited*/
"phone"": "12345" }"; /*Added*/
}
编辑 1 - 更复杂的示例
const string json1 =
@"{
""firstName"": ""John"",
""lastName"": ""Smith"",
""age"": 25,
""address"":
{
""streetAddress"": ""21 2nd Street"",
""city"": ""New York"",
""state"": ""NY"",
""postalCode"": ""10021""
},
""phoneNumber"":
[
{
""type"": ""home"",
""number"": ""212 555-1234""
},
{
""type"": ""fax"",
""number"": ""646 555-4567""
}
]
}";
const string json2 =
@"{
""firstName"": ""John2"",
""lastName"": ""robert"",
""age"": 25,
""address"":
{
""state"": ""FL"",
},
""phoneNumber"":
[
{
""type"": ""fax"",
""number"": ""222 222-2222""
},
{
""type"": ""iphone"",
""number"": ""111 111-1111""
}
]
}";
const string json3 =
@"{
""firstName"": ""John3"",
""father"": ""guy""
}";
const string expectedResult =
@"{
""firstName"": ""John3"",
""lastName"": ""robert"",
""age"": 25,
""father"": ""guy"",
""address"":
{
""streetAddress"": ""21 2nd Street"",
""city"": ""New York"",
""state"": ""FL"",
""postalCode"": ""10021""
},
""phoneNumber"":
[
{
""type"": ""home"",
""number"": ""212 555-1234""
},
{
""type"": ""fax"",
""number"": ""222 222-2222""
},
{
""type"": ""iphone"",
""number"": ""111 111-1111""
}
]
}";
编辑 2
在对需求进行了更多思考之后,我发现更复杂的示例永远无法按原样工作。级联功能将无法知道某个电话号码是否已被修改或是否是新号码。为了使它工作,每个子实体都应该有一个唯一的标识符。
【问题讨论】:
-
有趣。这不是一个典型的用例,所以如果存在任何库,我会感到非常惊讶。我现在正在写自己的。
-
不确定它是否有助于您解决特定问题,但您可以查看 pietschsoft.com/post/2008/02/… 和 json.codeplex.com
-
不确定我是否正确理解了这个例子,但想知道结果应该是
Albert Smith还是'John Albert'(根据你所展示的) -
我更新了我的答案以响应您的更改。但是,我将合并数组作为练习留给读者。 :)
标签: c# json parsing serialization