我是 json 新手,因为我正在获取以下 json 字符串。
我需要使用 c# 在 asp.net 中执行以下输出 1,2,6,3,5,4(获取以逗号分隔的 id 对象)
[
{
"id":1,
"children":
[
{
"id":2,
"children" :
[
{"id":6},
{"id":3},
]
}
]
},
{
"id":5
},
{
"id":4
}
]
代码背后的工作:
public class GetId
{
public string id { get; set; }
}
List<GetId> myDeserializedObjList = (List<GetId>)Newtonsoft.Json.JsonConvert.DeserializeObject(nestable_list_1_output.InnerText, typeof(List<GetId>));
for(int i=0; i < myDeserializedObjList.Count;i++)
{
string Id = myDeserializedObjList[i].id.ToString();
}
实现这个之后我只得到 1,5,4 ...我也想要子对象 Ids..
谢谢
最佳答案
Json 到 C# 转换器不能很好地处理这种递归定义。事实上你的类(class)很简单
public class ID
{
public int id { get; set; }
public List<ID> children { get; set; }
}
您的 json 现在可以是任意深度。您所要做的就是
var myDeserializedObjList = JsonConvert.DeserializeObject<List<ID>>(json);
您现在可以递归地获取结果
PrintMyObject(myDeserializedObjList);
void PrintMyObject(List<ID> ids)
{
foreach (var id in ids)
{
Console.WriteLine(id.id);
if (id.children != null)
PrintMyObject(id.children);
}
}
为了使答案完整:这部分是一个 Linq 技巧,用于展平递归数据结构。
Func<List<ID>, IEnumerable<ID>> flattenList = null;
flattenList = l => l.SelectMany(x => new[] { x }.Concat( x.children==null
? Enumerable.Empty<ID>()
: flattenList(x.children)));
var flatList = flattenList(myDeserializedObjList).ToList();
关于c# - 从c#中的json字符串中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32391408/