我有一组数组数组作为JSON,下面包含一个样本
F1 = Feature #1
P1 = Point #1
X / Y = Coordinates
所以F1P1X
是特征#1的第1点的X值。
[
[
[F1P1X,F1P1Y,null],
[F1PnX,F1PnY,null]
],
[
[F2P1X,F2P1Y,null],
[F2PnX,F2PnY,null]
],
[
[FnP1X,FnP1Y,null],
[FnPnX,FnPnY,null]
]
]
以下是我用来从文件中获取上述JSON的代码:
string json = File.ReadAllText("ABC.json");
JObject obj = JObject.Parse(json);
JToken token = obj.SelectToken("$.features[?(@.name == 'X')]['XY']");
var paths = JToken.Parse(token.ToString()).SelectToken("XYZ");
接下来,我需要使用各种数组构建字符串。如何获取二级数组(该功能)以便我可以处理其最内层的数组(功能上的点)?结尾将是List<string>
,其中每个字符串是一个特征(JSON中的第二级数组),最里面的数组是构成该特征的点。我可以处理字符串操作,但首先我需要从JSON中获取数组。
答案 0 :(得分:0)
很好的选择是使用JSON的Json.NET nuget包。我已经为你创建了测试方法。
//Read your json file
string json = File.ReadAllText("ABC.json");
//deserialize
F1P1X[][][] yourArrayOfArraysOfArrays = JsonConvert.DeserializeObject<F1P1X[][][]>(json).ToList();
public class F1P1X
{
public string Feature { get; set; }
public string Point { get; set; }
public string Coordinates { get; set; }
}
public static void Test()
{
F1P1X[] test1Array = new[]
{
new F1P1X
{
Feature = "F1",
Point = "P1",
Coordinates = "X1"
},
new F1P1X
{
Feature = "F2",
Point = "P2",
Coordinates = "X2"
},
};
F1P1X[] test2Array = new[]
{
new F1P1X
{
Feature = "F3",
Point = "P3",
Coordinates = "X3"
},
new F1P1X
{
Feature = "F4",
Point = "P4",
Coordinates = "X4"
},
};
F1P1X[][] test = {test1Array, test2Array};
F1P1X[][] test2 = { test1Array, test2Array };
F1P1X[][][] top = {test, test2};
//array of arrays of arrays as JSON
string json = JsonConvert.SerializeObject(top);
List<F1P1X[][]> arrays = JsonConvert.DeserializeObject<F1P1X[][][]>(json).ToList();
foreach (F1P1X[][] item in arrays)
{
foreach (F1P1X[] f1P1X in item)
{
foreach (F1P1X p1X in f1P1X)
{
//do some magic
}
}
}
// or use linq
var result = arrays.SelectMany(x => x.SelectMany(y => y.Where(z => z.Coordinates == "X1")));
}
此linq语句返回功能列表
List<string> result = arrays.SelectMany(x => x.SelectMany(y => y.Select(z => z.Feature))).ToList();