簡體   English   中英

如何反序列化復雜的嵌套JSON?

[英]How can I deserialise a complex and nested JSON?

在我的c#項目中,我想訪問復雜且嵌套的JSON中的特定信息(POI 名稱距離 )。

此JSON是Azure Maps API調用的結果。

我試圖將其反序列化為一個對象。 但是此JSON太復雜了,我無法做到。

提取所需信息的最佳方法是什么?

{
  "summary": {
    "query": "university",
    "queryType": "NON_NEAR",
    "queryTime": 103,
    "numResults": 1,
    "offset": 0,
    "totalResults": 216684,
    "fuzzyLevel": 1,
    "geoBias": {
      "lat": 48.008446,
      "lon": 7.821583
    }
  },
  "results": [
    {
      "type": "POI",
      "id": "DE/POI/p0/1505647",
      "score": 2.574,
      "dist": 774.6544330765787,
      "info": "search:ta:276009006412786-DE",
      "poi": {
        "name": "Universität Freiburg Medizinische Fakultät",
        "phone": "+(49)-(761)-27072350",
        "url": "www.med.uni-freiburg.de",
        "categories": [
          "college/university"
        ],
        "classifications": [
          {
            "code": "COLLEGE_UNIVERSITY",
            "names": [
              {
                "nameLocale": "en-US",
                "name": "college/university"
              }
            ]
          }
        ]
      },
      "address": {
        "streetName": "Elsässer Straße",
        "municipalitySubdivision": "Mooswald",
        "municipality": "Freiburg im Breisgau",
        "countrySecondarySubdivision": "Freiburg im Breisgau",
        "countrySubdivision": "Baden-Württemberg",
        "postalCode": "79110",
        "countryCode": "DE",
        "country": "Germany",
        "countryCodeISO3": "DEU",
        "freeformAddress": "Elsässer Straße, 79110 Freiburg Im Breisgau"
      },
      "position": {
        "lat": 48.00894,
        "lon": 7.83197
      },
      "viewport": {
        "topLeftPoint": {
          "lat": 48.00984,
          "lon": 7.83063
        },
        "btmRightPoint": {
          "lat": 48.00804,
          "lon": 7.83331
        }
      },
      "entryPoints": [
        {
          "type": "main",
          "position": {
            "lat": 48.00931,
            "lon": 7.83259
          }
        }
      ]
    }
  ]
}

第1步:在JSON解析器網站(例如https://jsonparser.org)中解析JSON,這將幫助您理解內容以及如何將其轉換為對象。 例如,您的JSON字符串給出以下結果:

在此處輸入圖片說明

步驟2:打開此網站的查詢工具,這將幫助您找到所需信息的對象路徑。 例如,對於您的JSON字符串,訪問POI名稱:

在此處輸入圖片說明

步驟3:在Visual Studio項目中,在共享庫中安裝NuGet包:Newtonsoft.Json和Microsoft.CSharp。 如果要在單獨的庫中處理JSON,也請在主項目中安裝Newtonsoft.Json NuGet軟件包。

步驟4:如果JSONstring是您的JSON字符串:

using Newtonsoft.Json;

dynamic NewObject = JsonConvert.DeserializeObject<dynamic>(JSONstring);


string Name = NewObject.results[0].poi.name;

string Distance = NewObject.results[0].dist;

您可能至少有2種解決方案:

您可以創建可反映您期望的json內容的類

public class MyJSON
{
  public Summary summary { get; set; }

  public List<Result> results { get; set; }
  ...
}

public class Summary
{
   public string query { get; set; }
   ...
}

然后您可以使用Newtonsoft.Json反序列化

JsonConvert.DeserializeObject<MyJSON>(jsonstring);

或者,您可以直接反序列化為動態對象並按名稱直接訪問屬性。

  dynamic data = JsonConvert.DeserializeObject<dynamic>(jsonstring);      
  string query = data[0].summary.query;

解決方案1要求您首先創建類,但訪問速度更快且更安全(不易出現錯誤的命名或數據結構更改)

解決方案2更加不穩定和靈活,您只需訪問所需的內容即可。 但是,如果嘗試訪問json對象中不存在的屬性,則可能會出現異常。

我通過json2csharp轉換了json,然后可以使用Newtonsoft將其反序列化

RootObject root = JsonConvert.DeserializeObject(JSONstring)

   public class GeoBias
    {
        public double lat { get; set; }
        public double lon { get; set; }
    }

    public class Summary
    {
        public string query { get; set; }
        public string queryType { get; set; }
        public int queryTime { get; set; }
        public int numResults { get; set; }
        public int offset { get; set; }
        public int totalResults { get; set; }
        public int fuzzyLevel { get; set; }
        public GeoBias geoBias { get; set; }
    }

    public class Name
    {
        public string nameLocale { get; set; }
        public string name { get; set; }
    }

    public class Classification
    {
        public string code { get; set; }
        public List<Name> names { get; set; }
    }

    public class Poi
    {
        public string name { get; set; }
        public string phone { get; set; }
        public string url { get; set; }
        public List<string> categories { get; set; }
        public List<Classification> classifications { get; set; }
    }

    public class Address
    {
        public string streetName { get; set; }
        public string municipalitySubdivision { get; set; }
        public string municipality { get; set; }
        public string countrySecondarySubdivision { get; set; }
        public string countrySubdivision { get; set; }
        public string postalCode { get; set; }
        public string countryCode { get; set; }
        public string country { get; set; }
        public string countryCodeISO3 { get; set; }
        public string freeformAddress { get; set; }
    }

    public class Position
    {
        public double lat { get; set; }
        public double lon { get; set; }
    }

    public class TopLeftPoint
    {
        public double lat { get; set; }
        public double lon { get; set; }
    }

    public class BtmRightPoint
    {
        public double lat { get; set; }
        public double lon { get; set; }
    }

    public class Viewport
    {
        public TopLeftPoint topLeftPoint { get; set; }
        public BtmRightPoint btmRightPoint { get; set; }
    }

    public class Position2
    {
        public double lat { get; set; }
        public double lon { get; set; }
    }

    public class EntryPoint
    {
        public string type { get; set; }
        public Position2 position { get; set; }
    }

    public class Result
    {
        public string type { get; set; }
        public string id { get; set; }
        public double score { get; set; }
        public double dist { get; set; }
        public string info { get; set; }
        public Poi poi { get; set; }
        public Address address { get; set; }
        public Position position { get; set; }
        public Viewport viewport { get; set; }
        public List<EntryPoint> entryPoints { get; set; }
    }

    public class RootObject
    {
        public Summary summary { get; set; }
        public List<Result> results { get; set; }
    }

暫無
暫無

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

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