很抱歉出现类似nube的问题,但是已经退休了一段时间,我发现自己忘记了一些事情。
给出以下示例json字符串:
{
"range": [
{ "num": 0 },
{ "num": 1 },
{ "num": 2 },
{ "num": 3 },
{ "num": 4 },
{ "num": 5 },
{ "num": 6 },
{ "num": 7 },
{ "num": 8 },
{ "num": 9 }
],
"friends": [
{
"id": 0,
"name": "Christian Cruz"
},
{
"id": 1,
"name": "Hunter Moon"
},
{
"id": 2,
"name": "Holden Gentry"
}
]
}
我希望能够读取数据中每一行的根值(在这种情况下为“范围”和“朋友”),然后解析其余值。
void Main()
{
var json = File.ReadAllText(@"c:\data\sample.json");
JObject obj = JObject.Parse(json);
foreach(JProperty child in obj.Children())
{
}
}
我陷入困境的地方是遍历children集合(foreach(JProperty child ...)),我可以读取 array 中的项目(例如“ num”,“ id”和“名称”),但我无法读取根值(例如“范围”和“朋友”)
任何能借给老人的帮助将不胜感激。
答案 0 :(得分:2)
将其反序列化为C#对象要容易得多,例如:
public class RootObject
{
public List<Range> range { get; set; }
public List<Friend> friends { get; set; }
}
public class Range
{
public int num { get; set; }
}
public class Friend
{
public int id { get; set; }
public string name { get; set; }
}
现在您可以像这样使用反序列化:
var root = JsonConvert.DeserializeObject<RootObject>(json);
并使用数据:
foreach (var range in root.Range)
{
//Do stuff
}
foreach (var friend in root.Friends)
{
//Do stuff
}
答案 1 :(得分:0)
使用下面的这个小的递归函数,您可以解压JSON以查看属性和值,而无需创建任何类
static void Main(string[] args)
{
var json = "{\"range\":[{\"num\":0},{\"num\":1},{\"num\":2},{\"num\":3},{\"num\":4},{\"num\":5},{\"num\":6},{\"num\":7},{\"num\":8},{\"num\":9}],\"friends\":[{\"id\":0,\"name\":\"Christian Cruz\"},{\"id\":1,\"name\":\"Hunter Moon\"},{\"id\":2,\"name\":\"Holden Gentry\"}]}";
JObject obj = JObject.Parse(json);
void UnpackJson(JToken jobj, int indent)
{
if (jobj == null)
return;
var name = (jobj as JProperty)?.Name;
if (name != null)
{
Console.Write(new string(' ', indent) + name + " :\n");
indent += 4;
}
foreach (var child in jobj.Children())
{
var chname = (child as JProperty)?.Name;
if (chname != null)
Console.Write(new string(' ', indent) + chname + " : ");
var value = (child as JProperty)?.Value;
if (child.Values().Count() > 1)
{
if (chname != null || name != null)
Console.WriteLine();
IEnumerable<JToken> jt = (value is JArray) ? child.Values() : child.Children();
foreach (var val in jt)
UnpackJson(val, indent + 4);
}
else
{
if (value != null)
Console.WriteLine(value);
}
}
}
UnpackJson(obj, 0);
Console.Read();
}
输出:
range :
num : 0
num : 1
num : 2
num : 3
num : 4
num : 5
num : 6
num : 7
num : 8
num : 9
friends :
id : 0
name : Christian Cruz
id : 1
name : Hunter Moon
id : 2
name : Holden Gentry
答案 2 :(得分:0)
您可以使用SelectTokens,将json放入列表中,然后遍历JProperty。
var files = JObject.Parse(YourJson);
var recList = files.SelectTokens("$").ToList();
foreach (JProperty item in recList.Children())
{
var key = item.Name.ToString(); //store the root item here
var value = item.Value.ToString();
//Do your stuffs
}