使用json.net反序列化json对象数组

时间:2019-07-12 10:55:07

标签: c# json

我想反序列化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是字段

1 个答案:

答案 0 :(得分:1)

您发布的以下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);
        }
    }
}