2017-01-13 102 views
0

我有數組作爲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

名單這不是有效的JSON ... –

回答

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();