[英]Retrieve data from json string in c#
I am new for json , as i am getting following json string. 我是json的新手,因为我正在关注json字符串。
i need following output 1,2,6,3,5,4 (get id object with comma separated) in asp.net with c# 我需要使用c#在asp.net中跟随以下输出1,2,6,3,5,4(获取用逗号分隔的ID对象)
[
{
"id":1,
"children":
[
{
"id":2,
"children" :
[
{"id":6},
{"id":3},
]
}
]
},
{
"id":5
},
{
"id":4
}
] ]
Code Behind work : 工作背后的代码:
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();
}
after implement this i get only 1,5,4 ...also i want children object Ids.. 实施后,我只得到1,5,4 ...我也希望孩子们获得对象ID。
Thanks 谢谢
Json to c# converters will not work great with this recursive definitions. Json到c#的转换器不适用于此递归定义。 In fact your class is simple 其实你的课很简单
public class ID
{
public int id { get; set; }
public List<ID> children { get; set; }
}
Your json can now be in any depth. 您的json现在可以处于任何深度。 All you have to do is 您要做的就是
var myDeserializedObjList = JsonConvert.DeserializeObject<List<ID>>(json);
You can now get the results recursively 您现在可以递归获得结果
PrintMyObject(myDeserializedObjList);
void PrintMyObject(List<ID> ids)
{
foreach (var id in ids)
{
Console.WriteLine(id.id);
if (id.children != null)
PrintMyObject(id.children);
}
}
To make the answer complete: This part is a Linq trick, to flatten your recursive data structure. 要使答案完整:这是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();
Use json2csharp to generate correct class structure - 使用json2csharp生成正确的类结构-
public class Child2
{
public int id { get; set; }
}
public class Child
{
public int id { get; set; }
public List<Child2> children { get; set; }
}
public class RootObject
{
public int id { get; set; }
public List<Child> children { get; set; }
}
Use this class RootObject
to deserialize json response. 使用此类RootObject
反序列化json响应。
You should include children in your definition of the GetId class. 您应该在GetId类的定义中包含子级。
public class GetId
{
public int id { get; set; }
public List<GetId> children { get; set; }
}
Then when collecting the id's, you do it using a recursive call to make sure you get all ids in the lower structures. 然后,在收集ID时,您可以使用递归调用来确保所有的ID都位于下部结构中。
private void CollectIdValues(List<GetId> list, List<int> ids){
foreach(GetId item in list){
ids.Add(item.id);
if(item.children != null){
CollectIdValues(item.children, ids);
}
}
}
List<GetId> myDeserializedObjList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<GetId>>(jsonString));
List<int> allIds = new List<int>();
CollectIdValues(myDeserializedObjList, allIds);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.