gpt4 book ai didi

c# - 在 C# 中反序列化 Zomato JSON 响应

转载 作者:太空宇宙 更新时间:2023-11-03 20:58:10 24 4
gpt4 key购买 nike

我正在使用 Zomato API,并且收到以下 JSON 响应:

{
"categories": [
{
"categories": {
"id": 1,
"name": "Delivery"
}
},
{
"categories": {
"id": 2,
"name": "Dine-out"
}
},
{
"categories": {
"id": 3,
"name": "Nightlife"
}
},
{
"categories": {
"id": 4,
"name": "Catching-up"
}
},
{
"categories": {
"id": 5,
"name": "Takeaway"
}
},
{
"categories": {
"id": 6,
"name": "Cafes"
}
},
{
"categories": {
"id": 7,
"name": "Daily Menus"
}
},
{
"categories": {
"id": 8,
"name": "Breakfast"
}
},
{
"categories": {
"id": 9,
"name": "Lunch"
}
},
{
"categories": {
"id": 10,
"name": "Dinner"
}
},
{
"categories": {
"id": 11,
"name": "Pubs & Bars"
}
},
{
"categories": {
"id": 13,
"name": "Pocket Friendly Delivery"
}
},
{
"categories": {
"id": 14,
"name": "Clubs & Lounges"
}
}
]
}

我想反序列化这个响应,我创建了以下类:

public class CategoriesTop
{
public List<CategoriesBottom> categories { get; set; }
}
public class CategoriesBottom
{
public Categorie categorie { get; set; }
}
public class Categorie
{
public int id { get; set; }
public string name { get; set; }
}

我正在使用这段代码来获取响应:

public Form1()
{
InitializeComponent();

HttpWebRequest webRequest =
WebRequest.Create("https://developers.zomato.com/api/v2.1/categories")
as HttpWebRequest;
HttpWebResponse webResponse = null;
webRequest.Headers.Add("X-Zomato-API-Key", "509ce9e4863960cdc076fb3817cc238e");
//you can get KeyValue by registering with Zomato.
webRequest.Method = "GET";
webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK)
{
StreamReader responseReader = new
StreamReader(webResponse.GetResponseStream());
string responseData = responseReader.ReadToEnd();
//XmlDocument doc = new XmlDocument();
//doc.LoadXml(responseData);
//XmlNodeReader xmlReader = new XmlNodeReader(doc);
//DataSet ds = new DataSet();
//ds.ReadXml(xmlReader);
List<CategoriesBottom> l = JsonConvert.DeserializeObject<List<CategoriesBottom>>(responseData);
foreach(CategoriesBottom c in l)
{
cmbCatName.Items.Add(c.categorie.name);
}
}
}

当我运行程序时,我在 JSON.Convert 行收到错误:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WindowsFormsApp1.CategoriesBottom]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

所以我认为反序列化代码有问题,或者类定义不正确。任何帮助将不胜感激。

最佳答案

尝试将属性更改为匹配 json 数据:

public class CategoriesBottom
{
public Categorie categories { get; set; }
}

同时序列化您的 CategoriesTop 类型:

CategoriesTop ct = JsonConvert.DeserializeObject<CategoriesTop>(responseData);

关于c# - 在 C# 中反序列化 Zomato JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48276033/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com