“最简单”的方法是Dictionary<Object, Object>
. 由于 PHP 的数据类型如此松散,因此 anObject
会给您更大的灵活性。然后 .NET 会根据需要将值装箱。就像是:
/* $final */
IDictionary<Object, Object> final = new Dictionary<Object, Object>();
/* $final["header"] */
// by keeping this separated then joining it to final, you avoid having
// to cast it every time you need to reference it since it's being stored
// as an Object
IDictionary<Object, Object> header = new Dictionary<Object, Object> {
{ "title", "Test" },
{ "num", 5 },
{ "limit", 5 }
};
// above short-hand declaration is the same as doing:
// header.Add("title", "Test");
// header.Add("num", 5);
// header.Add("limit", 5);
final.Add("header", header);
/* $final["data"] */
IList<Object> data = new List<Object>();
// not sure where `results` comes from, but I'll assume it's another type of
// IDictionary<T1,T2>
foreach (KeyValuePair<Object, Object> kvp in results)
{
data.Add(new Dictionary<Object, Object> {
{ "primary", "Primary" },
{ "secondary", "Secondary" },
{ "image", "test.png" },
{ "onclick", "alert('You clicked on the Primary');" }
});
}
final.Add("data", data);
请记住,这肯定不是最优化的,但确实使它最接近您正在使用的内容。
从那里,您可以使用库(如Newtsonsoft Json)并序列化信息。
JsonConvert.SerializeObject(final);
测试和工作:
我将$results
/results
作为相等的值添加到两者(foo->Foo,bar->Bar,baz->Baz),然后将两者序列化为 JSON 并产生相同的结果:
[{"header":{"title":"Test","num":5,"limit":5},"data":[{"primary":"Primary","secondary":"Secondary", "image":"test.png","onclick":"alert('You clicked on Primary');"},{"primary":"Primary","secondary":"Secondary","image": "test.png","onclick":"alert('你点击了 Primary');"},{"primary":"Primary","secondary":"Secondary","image":"test.png ","onclick":"alert('你点击了主节点');"}]}]