簡體   English   中英

使用C#訪問JSON文件中的元素

[英]Access Elements in JSON File Using C#

我有這樣的JSON結果

{
   "authenticationResultCode":"ValidCredentials",
   "brandLogoUri":"http:\/\/dev.virtualearth.net\/Branding\/logo_powered_by.png",
   "copyright":"Copyright © 2011 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
   "resourceSets":[
      {
         "estimatedTotal":1,
         "resources":[
            {
               "__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
               "bbox":[
                  47.636257744012461,
                  -122.13735364288299,
                  47.643983179153814,
                  -122.12206713944467
               ],
               "name":"1 Microsoft Way, Redmond, WA 98052",
               "point":{
                  "type":"Point",
                  "coordinates":[
                     47.640120461583138,
                     -122.12971039116383
                  ]
               },
               "address":{
                  "addressLine":"1 Microsoft Way",
                  "adminDistrict":"WA",
                  "adminDistrict2":"King Co.",
                  "countryRegion":"United States",
                  "formattedAddress":"1 Microsoft Way, Redmond, WA 98052",
                  "locality":"Redmond",
                  "postalCode":"98052"
               },
               "confidence":"High",
               "entityType":"Address",
               "geocodePoints":[
                  {
                     "type":"Point",
                     "coordinates":[
                        47.640120461583138,
                        -122.12971039116383
                     ],
                     "calculationMethod":"InterpolationOffset",
                     "usageTypes":[
                        "Display"
                     ]
                  },
                  {
                     "type":"Point",
                     "coordinates":[
                        47.640144601464272,
                        -122.12976671755314
                     ],
                     "calculationMethod":"Interpolation",
                     "usageTypes":[
                        "Route"
                     ]
                  }
               ],
               "matchCodes":[
                  "Good"
               ]
            }
         ]
      }
   ],
   "statusCode":200,
   "statusDescription":"OK",
   "traceId":"b0b1286504404eafa7e7dad3e749d570"
}

我想獲取一個對象列表,每個對象都將包含坐標值

那么如何通過名稱訪問這些元素呢?

我正在使用C#作為背后的代碼。

您可以將Json.NET之類的軟件包用於此任務。

並且您可以通過從http://json2csharp.com/提供json字符串輕松生成類

那么您可以訪問以下項的屬性

RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonText);

以下是從json2csharp為給定的json生成的類

public class Point
{
    public string type { get; set; }
    public List<double> coordinates { get; set; }
}

public class Address
{
    public string addressLine { get; set; }
    public string adminDistrict { get; set; }
    public string adminDistrict2 { get; set; }
    public string countryRegion { get; set; }
    public string formattedAddress { get; set; }
    public string locality { get; set; }
    public string postalCode { get; set; }
}

public class GeocodePoint
{
    public string type { get; set; }
    public List<double> coordinates { get; set; }
    public string calculationMethod { get; set; }
    public List<string> usageTypes { get; set; }
}

public class Resource
{
    public string __type { get; set; }
    public List<double> bbox { get; set; }
    public string name { get; set; }
    public Point point { get; set; }
    public Address address { get; set; }
    public string confidence { get; set; }
    public string entityType { get; set; }
    public List<GeocodePoint> geocodePoints { get; set; }
    public List<string> matchCodes { get; set; }
}

public class ResourceSet
{
    public int estimatedTotal { get; set; }
    public List<Resource> resources { get; set; }
}

public class RootObject
{
    public string authenticationResultCode { get; set; }
    public string brandLogoUri { get; set; }
    public string copyright { get; set; }
    public List<ResourceSet> resourceSets { get; set; }
    public int statusCode { get; set; }
    public string statusDescription { get; set; }
    public string traceId { get; set; }
}

由於您似乎已經在使用DataContractJsonSerializer ,因此請繼續使用。 反序列化json的最佳方法是首先定義一個模型,該模型將捕獲相關數據,例如

public class JsonModel
{
    public int StatusCode { get; set; }
    public string StatusDescription { get; set; }
    public string TraceId { get; set; }
    ...
}

接下來,裝飾模型,使其適合反序列化

[DataContract]
public class JsonModel
{
    [DataMember(Name = "statusCode")]
    public int StatusCode { get; set; }
    [DataMember(Name = "statusDescription")]
    public string StatusDescription { get; set; }
    [DataMember(Name = "traceId")]
    public string TraceId { get; set; }
    ...
}

最后,執行反序列化

using (var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonData))) 
{    
    var serializer = new DataContractJsonSerializer(typeof(JsonModel));
    var model = (JsonModel) serializer.ReadObject(memoryStream);  
    Console.WriteLine(model.StatusCode);
}

那么如何通過名稱訪問這些元素呢?

反序列化的另一個選項可以使您能夠按名稱引用屬性,這將使用dynamic對象,例如

var model = new JavaScriptSerializer().Deserialize<dynamic>(jsonData);
Console.WriteLine(model["statusCode"]);

從下面的URL將所有Bing Maps REST服務的類添加到您的項目中:

JSON數據合約

然后,確保您添加using指令:

using BingMapsRESTService.Common.JSON;

並按如下方式讀取字符串(其中stream是json的流):

var d = new DataContractJsonSerializer(typeof(Response));
var o = d.ReadObject(stream);

暫無
暫無

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

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