首頁 C# 強型別解析JSON字串範例
文章
Cancel

C# 強型別解析JSON字串範例

前置步驟

安裝Newtonsoft.Json

Desktop View

1
NuGet\Install-Package Newtonsoft.Json -Version 13.0.3

開始

最初API或AJAX調用成功, 在C#下中斷點,應該可以看到類似下圖的樣子

Desktop View

進一步使用分析Json 格式會看到如下

Desktop View

這時候我們就可以開始根據Json 格式製作C#強型別存取Json的Class了

解析的語法如下

1
2
3
4
5
6
7
8
var settings = new JsonSerializerSettings
  {
      ContractResolver = new DefaultContractResolver
      {
          NamingStrategy = new SnakeCaseNamingStrategy() // 或其他策略,如 CamelCaseNamingStrategy
      }
  };
JsonResponse mapsResponse = JsonConvert.DeserializeObject<JsonResponse>(response.Content, settings);//settings依情況而定,不一定要打

其中JsonResponse裡面有強型別JSON結構

如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class JsonResponse
{
    [JsonProperty("geocoded_waypoints")]
    public List<geocoded_waypoints> geocoded_waypoints { get; set; }
}
public class geocoded_waypoints
{
    [JsonProperty("geocoder_status")]
    public string geocoder_status { get; set; }

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

    [JsonProperty("types")]
    public List<string> Types { get; set; }
}

要注意的是JsonProperty內容字串要與JSON一致

Desktop View

下中斷點會長這樣

Desktop View

JSON字串-假資料測試

方法1 自己打

模擬輸入假的JSON字串,以便進行測試

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    /// <summary>
    /// 使用方式 var test = GetRootObject();
    /// </summary>
    public static RootObject GetRootObject()
    {
        var json = @"{
        ""geocoded_waypoints"": [
            {
                ""geocoder_status"": ""OK"",
                ""place_id"": ""ChIJB0guq-amQjQRg-Bq2akhxEU"",
                ""types"": [
                    ""street_address""
                ]
            },
            {
                ""geocoder_status"": ""OK"",
                ""partial_match"": true,
                ""place_id"": ""ChIJS1h-WtOrQjQR8juhInQJddw"",
                ""types"": [
                    ""establishment"",
                    ""point_of_interest"",
                    ""school"",
                    ""secondary_school""
                ]
            }
        ]
    }";
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new DefaultContractResolver
            {
                NamingStrategy = new SnakeCaseNamingStrategy() // 或其他策略,如 CamelCaseNamingStrategy
            }
        };
        // 使用Newtonsoft.Json反序列化為物件
        var rootObject = JsonConvert.DeserializeObject<RootObject>(json, settings);
        return rootObject;
    }
    public class RootObject
    {
        public List<GeocodedWaypoint> GeocodedWaypoints { get; set; }
    }
    public class GeocodedWaypoint
    {
        public string GeocoderStatus { get; set; }
        public string PlaceId { get; set; }
        public List<string> Types { get; set; }
    }

Desktop View

方法2 給Json請GPT生成

ChatGPT範例指令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
示範如何在C# 模擬這個JSON輸入
{
   "geocoded_waypoints" : 
   [
      {
         "geocoder_status" : "OK",
         "place_id" : "ChIJB0guq-amQjQRg-Bq2akhxEU",
         "types" : 
         [
            "street_address"
         ]
      },
      {
         "geocoder_status" : "OK",
         "partial_match" : true,
         "place_id" : "ChIJS1h-WtOrQjQR8juhInQJddw",
         "types" : 
         [
            "establishment",
            "point_of_interest",
            "school",
            "secondary_school"
         ]
      }
   ]
}

備註

如果JSON字串覺得都一樣,但不曉得是為什麼讀不到資料的時候

要考慮可能會有JSON英文大小寫在交握時自動變更的可能性,依情況調整成不同的策略

Desktop View

1
2
3
4
5
6
7
var settings = new JsonSerializerSettings
{
    ContractResolver = new DefaultContractResolver
    {
        NamingStrategy = new SnakeCaseNamingStrategy() // 或其他策略,如 CamelCaseNamingStrategy
    }
};

輸入API網址的方式

安裝套件

RestSharp Desktop View

1
NuGet\Install-Package RestSharp -Version 110.2.0

使用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
RestClient client = new RestClient("https://www.binance.com/api/v3/ticker/price");
RestRequest request = new RestRequest();
var settings = new JsonSerializerSettings
{
    ContractResolver = new DefaultContractResolver
    {
        NamingStrategy = new SnakeCaseNamingStrategy() // 或其他策略,如 CamelCaseNamingStrategy
    }
};
RestResponse response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
    var mapsResponse = JsonConvert.DeserializeObject<Price>(response.Content, settings);
 
}

public class Price
{
    [JsonProperty("symbol")]
    public string symbol { get; set; }
    [JsonProperty("price")]
    public string price { get; set; }
}
本文由作者按照 CC BY 4.0 進行授權