How to filter JSON array in C#

前端 未结 3 1823
独厮守ぢ
独厮守ぢ 2020-12-10 08:03

I have spent a lot of time to find a solution for my problem.

In this example, I have 2 records in SetNavRecords array. The first one is \"Artikelnummer\" :

3条回答
  •  囚心锁ツ
    2020-12-10 08:34

    var tmpResult = JObject.Parse(File.ReadAllText(FileName));
    var resultObject = tmpResult["SetNavRecords"].Values("OfflineVerkaufspreis").Values()                                   
                .Where(n => n["Location_Code"].Value() == "MH");   
    

    This code will navigate to OfflineVerkaufspreis.Values and then filter them. But (I guess) you want to select the location that matches your Where clause and then also selects the parent details.

    You can use Select to select all the information you are really interested in.

    var resultObject = tmpResult["SetNavRecords"].Values("OfflineVerkaufspreis").Values()
               .Where(n => n["Location_Code"].Value() == "MH")
               .Select(n => new { Location = n, Context = n.Parent }).ToArray();
    

    Of course you can select just the information you really need instead of the entire Parent.

    To make this code more readable, I would suggest to create some classes that match the JSon input so that you can map the JSon to this graph of objects. It will make your Linq alot easier to write, read and understand.

    Update: In the comments is suggested to use: .Where(n => n["OfflineVerkaufspreis"]["Location_Code"] .... The problem with this approach is that in the end you don't know which of the OfflineVerkaufspreis actually matched your where clause...

提交回复
热议问题