反序列化嵌套JSON

时间:2019-02-23 18:37:55

标签: c# json

我可以使用一些帮助。我正在尝试反序列化Json文件,然后将其添加到列表中,以便可以将其放入C#应用程序中的表中。我得到一部分要生成的代码,但没有嵌套的区域。

我想计算属性的总数(在json中显示为“ features”)。然后,我想列出每个属性的“属性”。

任何帮助都会很棒。 -Rob

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


public class Program
{
    public static void Main()
    {
          WebClient client = new WebClient();
          string json = client.DownloadString("https://gis.nccde.org/agsserver/rest/services/CustomMaps/Ownership/MapServer/0/query?where=UPPER(SUBDIV)%20like%20'%25ENCLAVE%20AT%20ODESSA%25'&outFields=*&outSR=4326&f=json");            

        var myModel = JsonConvert.DeserializeObject<ParcelViewModel>(json);

        Console.WriteLine("Top Level ID: " + myModel.displayFieldName);

        Console.WriteLine("Property Count: " + myModel.features.Count);

        int i = 0;
        foreach (var fac in myModel.features)
        {
            i++;
            Console.WriteLine(" ");
            Console.WriteLine("Record Number: " + i);
            Console.WriteLine("Address: " + fac.address);
            Console.WriteLine("Owner: " + fac.CNTCTLAST);
            Console.WriteLine(" ");
        }
    }
}

public class ParcelViewModel
{
  public string displayFieldName { get; set; }
    public string geometryType { get; set; }
    public List<PropertyViewModel> features { get; set; }
}


public class PropertyViewModel
{
    public string address { get; set; }
    public string CNTCTLAST { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您使用的ViewModel结构不正确。属性应该是看着JSON响应的AttributeViewModel类型的对象。我设置了一些属性只是为了说明应如何设置。

    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        string json = client.DownloadString("https://gis.nccde.org/agsserver/rest/services/CustomMaps/Ownership/MapServer/0/query?where=UPPER(SUBDIV)%20like%20'%25ENCLAVE%20AT%20ODESSA%25'&outFields=*&outSR=4326&f=json");

        var myModel = JsonConvert.DeserializeObject<ParcelViewModel>(json);

        Console.WriteLine("Top Level ID: " + myModel.displayFieldName);

        Console.WriteLine("Property Count: " + myModel.features.Count);

        int i = 0;
        foreach (var fac in myModel.features)
        {
            i++;
            Console.WriteLine(" ");
            Console.WriteLine("Record Number: " + i);
            Console.WriteLine("Address: " + fac.attributes.ADDRESS);
            Console.WriteLine("Owner: " + fac.attributes.CNTCTLAST);
            Console.WriteLine(" ");
        }
    }

    public class ParcelViewModel
    {
        public string displayFieldName { get; set; }
        public string geometryType { get; set; }
        public List<FeatureViewModel> features { get; set; }
    }


    public class FeatureViewModel
    {
        public AttributeViewModel attributes { get; set; }            
    }

    public class AttributeViewModel
    {
        public string ADDRESS { get; set; }
        public string CNTCTLAST { get; set; }
    }