Почему десериализованные объектные поля становятся нулевыми, когда данные существуют? - PullRequest
0 голосов
/ 13 марта 2019

У меня есть объект json, который нужно десериализовать, я использую Json.NET для выполнения этих операций.

, когда это простой объект,это довольно легко сделать, но я не могу понять, как десериализовать эту строку

json

{
    "aspsp-list":
    [
        {
            "id":"424250495054504C",
            "bic":"BBPIPTPL",
            "bank-code":"0010",
            "aspsp-cde":"BBPI",
            "name":"BANCO BPI, SA",
            "logoLocation":"../img/corporate/theBank.jpg",
            "api-list":[{
                "consents":["BBPI/v1/consents"],
                "payments":["BBPI/v1/payments"],
                "accounts":["BBPI/v1/accounts"],
                "funds-confirmations":["BBPI/v1/funds-confirmations"]
            }]
        },
        {
            "id":"544F54415054504C",
            "bic":"TOTAPTPL",
            "bank-code":"0018",
            "aspsp-cde":"BST",
            "name":"BANCO SANTANDER TOTTA, SA",
            "logoLocation":"../img/openBank.svc",
            "api-list":[{
                "consents":["BBPI/v1/consents"],
                "payments":["BBPI/v1/payments"],
                "accounts":["BBPI/v1/accounts"],
                "funds-confirmations":["BST/v1/funds-confirmations"]
            }]
        }
    ]
}

Теперь код, который у меня пока есть:

internal class AspspListResponseResource 
{
    // Report with the list of supported ASPSPs. Each ASPSP will include the list of available API endpoints and the logo.
    [JsonProperty(PropertyName = "aspsp-list")]
    public AspspList[] AspspList { get; set; }

    public AspspListResponseResource() { /* Empty constructor to create the object */ }

     public AspspListResponseResource(string jsonString)
     {
        //var alrr = JsonConvert.DeserializeObject<AspspListResponseResource>(jsonString);

        JObject jObject = JObject.Parse(jsonString);
        JToken jUser = jObject["aspsp-list"];

        // The root object here is coming with certain fields as null, such as 'aspsp-cde', 'bank-code' and 'api-list'
        AspspListResponseResource root = JsonConvert.DeserializeObject<AspspListResponseResource>(jsonString);                        
     }
}

internal class Aspsp
{
    // ASPSP Id
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; } = "";

    // Bank Identifier Code
    [JsonProperty(PropertyName = "bic")]
    public string Bic { get; set; } = "";

    // IBAN Bank Identifier
    [JsonProperty(PropertyName = "bank-code")]
    public string BankCode { get; set; } = "";

    // ASPSP Code to use in the endpoint
    [JsonProperty(PropertyName = "aspsp-cde")]
    public string AspspCde { get; set; } = "";

    // Institution name
    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; } = "";

    // Bank logo location
    [JsonProperty(PropertyName = "logoLocation")]
    public string LogoLocation { get; set; } = "";

    // Bank Supported API List
    [JsonProperty(PropertyName = "api-list")]
    public ApiLink[] ApiList { get; set; }
}

internal class ApiLink
{
    // Consents Link List
    [JsonProperty(PropertyName = "consents")]
    public string[] Consents { get; set; } = { "" };

    // Payments Link List
    [JsonProperty(PropertyName = "payments")]
    public string[] Payments { get; set; } = { "" };

    // Accounts Link List
    [JsonProperty(PropertyName = "accounts")]
    public string[] Accounts { get; set; } = { "" };

    // Balances Link List
    [JsonProperty(PropertyName = "balances")]
    public string[] Balances { get; set; } = { "" };

    // Transaction Link List
    [JsonProperty(PropertyName = "transaction")]
    public string[] Transaction { get; set; } = { "" };

    // Funds-Confirmations Link List
    [JsonProperty(PropertyName = "funds-confirmations")]
    public string[] FundsConfirmations { get; set; } = { "" };

}

Сумма значений десериализованного объекта равна нулю, даже если у jsonString определенно есть данные.

Как мне поступить здесь?

Ответы [ 3 ]

2 голосов
/ 13 марта 2019

Структура вашего json:

{
 "aspsp-list":
    [
        {
            "id":"123123123",
            "bic":"BBPIPTPL",
            "bank-code":"0010",
            "aspsp-cde":"BBPI",
            "name":"BANCO BPI, SA",
            "logoLocation":"../img/corporate/theBank.jpg",
            "api-list":[{
                "consents":"",
                "payments":"",
                "accounts":"",
                "funds-confirmations":""
            }]
        },
        {
            "id":"1434231231",
            "bic":"TOTAPTPL",
            "bank-code":"0018",
            "aspsp-cde":"BST",
            "name":"BANCO SANTANDER TOTTA, SA",
            "logoLocation":"../img/openBank.svc",
            "api-list":[{
                "consents":"",
                "payments":"",
                "accounts":"",
                "funds-confirmations":""
            }]
        }
    ]
}

Это говорит нам о том, что у вас есть объект с массивом объектов, который называется Aspsp-list.

Если это то, что вы намеревались. Нам нужно создать объект, похожий на этот

public class RootJsonObject {
    public IEnumerable<Aspsp> Aspsp-list {get; set;}
}

Чтобы десериализовать это просто: JsonConvert.Deserialize<RootJsonObject>(/*your json string*/ value);

Если вы хотите работать только с массивом, вам нужно просто десериализовать его в IEnumerable/Array Но вам также нужно изменить свой json, чтобы он был просто массивом, а не объектом, обертывающим массив.

0 голосов
/ 14 марта 2019

Мне удалось заставить это работать сейчас, моя проблема была не в том, что я не мог десериализовать из-за типов данных или структуры (по крайней мере, не полностью, комментарий, в котором говорилось, что структура была неправильной, отчасти была правильной).

Итак, вот как я решил проблему:

-> Создал пустой конструктор для класса AspspListResponseResource, чтобы метод JsonConvert.DeserializeObject<T>(jsonString) мог создать экземпляр объекта, я думализ-за того, что единственный конструктор занял string, и поэтому для использования JsonConvert другого конструктора не было.

-> Поместить имена полей с помощью [JsonProperty(PropertyName = "")], но это все равно далоя десериализовал object как null или с некоторыми пустыми полями.

-> прокомментировал поля Transaction и FundsConfirmations класса ApiLink, эти поля были в документацииWeb API, поэтому я вставил их, но, глядя на строку json, которую я получил, похоже, что они не используются, поэтому я просто прокомментировал их

, и после этих изменений код теперь работает без нареканий:

Трескаe:

internal class AspspListResponseResource 
{
    // Report with the list of supported ASPSPs. Each ASPSP will include the list of available API endpoints and the logo.
    [JsonProperty(PropertyName = "aspsp-list")]
    public Aspsp[] AspspList { get; set; }

    public AspspListResponseResource() { /* Empty constructor to create the object */ }

     public AspspListResponseResource(string jsonString)
     {
        AspspListResponseResource root = JsonConvert.DeserializeObject<AspspListResponseResource>(jsonString);
        this.AspspList = root.AspspList;
     }
}

internal class Aspsp 
{
    // ASPSP Id
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; } = "";

    // Bank Identifier Code
    [JsonProperty(PropertyName = "bic")]
    public string Bic { get; set; } = "";

    // IBAN Bank Identifier
    [JsonProperty(PropertyName = "bank-code")]
    public string BankCode { get; set; } = "";

    // ASPSP Code to use in the endpoint
    [JsonProperty(PropertyName = "aspsp-cde")]
    public string AspspCde { get; set; } = "";

    // Institution name
    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; } = "";

    // Bank logo location
    [JsonProperty(PropertyName = "logoLocation")]
    public string LogoLocation { get; set; } = "";

    // Bank Supported API List
    [JsonProperty(PropertyName = "api-list")]
    public ApiLink[] ApiList { get; set; }
}

internal class ApiLink 
{
    // Consents Link List
    [JsonProperty(PropertyName = "consents")]
    public string[] Consents { get; set; } = { "" };

    // Payments Link List
    [JsonProperty(PropertyName = "payments")]
    public string[] Payments { get; set; } = { "" };

    // Accounts Link List
    [JsonProperty(PropertyName = "accounts")]
    public string[] Accounts { get; set; } = { "" };

    // Balances Link List
    [JsonProperty(PropertyName = "balances")]
    public string[] Balances { get; set; } = { "" };

    //// Transaction Link List
    //[JsonProperty(PropertyName = "transaction")]
    //public string[] Transaction { get; set; } = { "" };
    //
    //// Funds-Confirmations Link List
    //[JsonProperty(PropertyName = "funds-confirmations")]
    //public string[] FundsConfirmations { get; set; } = { "" };

}
0 голосов
/ 13 марта 2019

Вам необходимо создать конструктор для класса ApiLink, чтобы вы могли выполнять следующие действия:

var apiListRaw = new ApiLink(value["api-list"][0] as JObject);

Конструктор будет выглядеть примерно так:

public ApiLink(JObject json)
{
    Consensts = (string[])json["consents"];
    ...
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...