对象的C#解析JSON数组 [英] C# Parsing JSON array of objects

查看:112
本文介绍了对象的C#解析JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的对象在 JSON 格式的数组:

I have an array of objects like this in json format:

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

我要得到的是一个 [对象] 在C#中,其中一个对象包含所有的是一个JSON对象中的数据。问题是,我可以通过不会使类与此对象的喜欢这里的属性:

What I want to get is a object[] in C#, where one object contains all the data what is in one json object. The thing is, I can NOT make a class with the properties of this object like here:

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

由于我每次得到不同的结果回来了,但我知道它总是对象的数组。有人知道我怎么能弄到对象的数组回来了?

Because I get everytime different results back, but I know it's always an array of objects. Someone knows how I could manage to get an array of objects back?

修改

我要通过这个对象通过的writeObject到PowerShell的(结果)。因此,输出中只应数组中的对象

I have to pass this object to powershell via WriteObject(results). So the ouput should only be the object IN the array.

推荐答案

使用 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;
            }
        }
    }
}

这篇关于对象的C#解析JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆