[英]Working with C#: How do I iterate through a nested JSON using Newtonsoft.JSON?
[英]How to iterate through a nested JSON field using Newtonsoft.JSON & C# (And without using the dynamic keyword)
以下JSON文件包含字段“ tileproperties ”。 tileproperties中有0到19之间的数字 。
在这种特殊情况下,数字的数量是不确定的,JSON文件可能包含更多数量。
在所有这些数字的下面都有字段名称TileType ,它带有字符串值(例如“ river01”,“ river02”等)。
我想阅读此JSON文件并创建一个字典。 关键是数字,值是TileType 。 特别是我想使用Newtonsoft.JSON,C#,并且我无法使用dynamic关键字( 如关于堆栈溢出的类似问题所示 )
我不确定如何遍历tileproperties字段,因为它似乎没有格式化为数组(如data字段)。
{ "height":2,
"infinite":false,
"layers":[
{
"data":[1, 2, 11, 12, 1, 2, 6, 7, 16, 17, 6, 7],
"height":2,
"name":"Tile Layer 1",
"opacity":1,
"type":"tilelayer",
"visible":true,
"width":6,
"x":0,
"y":0
}],
"nextobjectid":1,
"orientation":"orthogonal",
"renderorder":"right-up",
"tiledversion":"1.1.2",
"tileheight":512,
"tilesets":[
{
"columns":5,
"firstgid":1,
"image":"..\/Art\/Sprites\/PrototypeTileSheet.png",
"imageheight":2048,
"imagewidth":2560,
"margin":0,
"name":"prototypeTiles",
"spacing":0,
"tilecount":20,
"tileheight":512,
"tileproperties":
{
"0":
{
"TileType":"river01"
},
"1":
{
"TileType":"river02"
},
"10":
{
"TileType":"start01"
},
"11":
{
"TileType":"end01"
},
"12":
{
"TileType":""
},
"13":
{
"TileType":""
},
"14":
{
"TileType":""
},
"15":
{
"TileType":"tree01"
},
"16":
{
"TileType":"tree02"
},
"17":
{
"TileType":""
},
"18":
{
"TileType":""
},
"19":
{
"TileType":""
},
"2":
{
"TileType":"unspecified01"
},
"3":
{
"TileType":""
},
"4":
{
"TileType":""
},
"5":
{
"TileType":"grass01"
},
"6":
{
"TileType":"grass02"
},
"7":
{
"TileType":""
},
"8":
{
"TileType":""
},
"9":
{
"TileType":""
}
},
"tilepropertytypes":
{
"0":
{
"TileType":"string"
},
"1":
{
"TileType":"string"
},
"10":
{
"TileType":"string"
},
"11":
{
"TileType":"string"
},
"12":
{
"TileType":"string"
},
"13":
{
"TileType":"string"
},
"14":
{
"TileType":"string"
},
"15":
{
"TileType":"string"
},
"16":
{
"TileType":"string"
},
"17":
{
"TileType":"string"
},
"18":
{
"TileType":"string"
},
"19":
{
"TileType":"string"
},
"2":
{
"TileType":"string"
},
"3":
{
"TileType":"string"
},
"4":
{
"TileType":"string"
},
"5":
{
"TileType":"string"
},
"6":
{
"TileType":"string"
},
"7":
{
"TileType":"string"
},
"8":
{
"TileType":"string"
},
"9":
{
"TileType":"string"
}
},
"tilewidth":512
},
{
"firstgid":21,
"source":"..\/..\/..\/..\/Artsource\/Assets\/Levels\/prototypeTileSet.tsx"
}],
"tilewidth":512,
"type":"map",
"version":1,
"width":6
}
如果只需要tileproperties
,而不需要其余tileproperties
,则可以使用以下方法:
var tileTypes = JObject.Parse(json)
["tilesets"][0]["tileproperties"].Children<JProperty>()
.ToDictionary(x => x.Name, x => x.Value["TileType"].Value<string>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.