小编典典

C#解析对象的JSON数组

json

我有以下json格式的对象数组:

{"results":[{"SwiftCode":"","City":"","BankName":"Deutsche Bank","Bankkey":"10020030","Bankcountry":"DE"},{"SwiftCode":"","City":"10891 Berlin","BankName":"Commerzbank Berlin (West)","Bankkey":"10040000","Bankcountry":"DE"}]}

我想要得到的是object[]C#中的代码,其中一个对象包含一个json对象中的所有数据。问题是,我可以 使一个类与此对象喜欢这里的属性:

public class Result
{
    public int SwiftCode { get; set; }
    public string City { get; set; }
    //      .
    //      .
    public string Bankcountry { get; set; }
}

因为我每次都会得到不同的结果,但是我知道它总是一个对象数组。有人知道我如何设法取回一系列对象?

编辑

我必须通过将该对象传递给powershell WriteObject(results)。因此,输出仅应是中的对象array


阅读 1057

收藏
2020-07-27

共1个答案

小编典典

像这样使用newtonsoft

using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;

class Program
{
    static void Main()
    {
        string json = "{'results':[{'SwiftCode':'','City':'','BankName':'Deutsche    Bank','Bankkey':'10020030','Bankcountry':'DE'},{'SwiftCode':'','City':'10891    Berlin','BankName':'Commerzbank Berlin (West)','Bankkey':'10040000','Bankcountry':'DE'}]}";

        var resultObjects = AllChildren(JObject.Parse(json))
            .First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))
            .Children<JObject>();

        foreach (JObject result in resultObjects) {
            foreach (JProperty property in result.Properties()) {
                // do something with the property belonging to result
            }
        }
    }

    // recursively yield all children of json
    private static IEnumerable<JToken> AllChildren(JToken json)
    {
        foreach (var c in json.Children()) {
            yield return c;
            foreach (var cc in AllChildren(c)) {
                yield return cc;
            }
        }
    }
}
2020-07-27