簡體   English   中英

使用json.net反序列化json對象數組

[英]Deserialize json object array with json.net

我想反序列化json對象數組。 我被卡住了。 我不知道如何使它對所提供的結構感到滿意。 對CustomerList(如下)執行操作會導致“無法反序列化當前JSON數組”異常。

我幾乎嘗試了一切

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

namespace ConsoleAppProva
{
    class Program
    {
        public class CustomerJson
        {
            [JsonProperty("IdPostazionee")]
            public Customer Customer { get; set; }
        }

        public class Customer
        {
            [JsonProperty("abc")]
            public string Firstname { get; set; }

            [JsonProperty("def")]
            public string Lastname { get; set; }

        }

        static void Main(string[] args)
        {
            string json = "{'IdPostazione':'1','StatoAutoma':'2','OriginalURL':'3','OriginalTitle':'lol','ChronicID':'xd'}";

            dynamic dynObj = JsonConvert.DeserializeObject(json);

            Console.WriteLine("{0} {1} {2}", dynObj.IdPostazione, dynObj.StatoAutoma, dynObj.OriginalURL);

            string jsoon = "{'IdPostazionee':['abc':'123','def':'456']}";

            Console.ReadLine();
        }
    }
}

我期望在控制台中看到數組的值:123,456。

IdPostazionee是數組。 abc,def是字段

您發布的以下JSON無效:

{
    'IdPostazionee': ['abc': '123', 'def': '456']
}

我想應該是:

{
    "IdPostazionee": [{
        "abc": "123",
        "def": "456"
    }]
}

或更好:

{
    "IdPostazionee": {
        "abc": "123",
        "def": "456"
    }
}

下面的代碼應該工作:

using Newtonsoft.Json;
using System;

namespace ConsoleApp11
{
    class Program
    {
        public class CustomerJson
        {
            [JsonProperty("IdPostazionee")]
            public Customer Customer { get; set; }
        }

        public class Customer
        {
            [JsonProperty("abc")]
            public string Firstname { get; set; }

            [JsonProperty("def")]
            public string Lastname { get; set; }

        }

        static void Main(string[] args)
        {
            string json = "{'IdPostazione':'1','StatoAutoma':'2','OriginalURL':'3','OriginalTitle':'lol','ChronicID':'xd'}";

            dynamic dynObj = JsonConvert.DeserializeObject(json);

            Console.WriteLine("{0} {1} {2}", dynObj.IdPostazione, dynObj.StatoAutoma, dynObj.OriginalURL);

            string jsoon = "{'IdPostazionee': {'abc':'123','def':'456'}}";

            var customerJson = JsonConvert.DeserializeObject<CustomerJson>(jsoon);

            Console.WriteLine(customerJson.Customer.Firstname);
            Console.WriteLine(customerJson.Customer.Lastname);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM