c#将json反序列化为List
c# Deserialize json into List
我有这段代码可以从 API link 中检索 Json 字符串。 Json 被反序列化并 returned 到文本框。只要只有 1 个 Json 值,它就可以完美运行,returned 超过 1 个值时它会崩溃并出现此错误:
Additional information: Cannot deserialize the current JSON array
(e.g. [1,2,3]) into type 'GW2_tradingPost.RootObject' because the type
requires a JSON object (e.g. {"name":"value"}) to deserialize
correctly.
To fix this error either change the JSON to a JSON object (e.g.
{"name":"value"}) or change the deserialized type to an array or a
type that implements a collection interface (e.g. ICollection, IList)
like List that can be deserialized from a JSON array.
JsonArrayAttribute can also be added to the type to force it to
deserialize from a JSON array.
我的研究之所以会发生这种情况,是因为 Json 不是列表,因此无处存放。
我试过这段代码和各种类似的代码。
List<RootObject> list = JsonConvert.DeserializeObject<List<RootObject>>(jsonReader.ToString());
return list;
这将 return 错误:
Error 1 Cannot implicitly convert type
'System.Collections.Generic.List' to
'GW2_tradingPost.RootObject' e:\mega\gw2_tradingpost\gw2_tradingpost\api_request.cs 34
我不完全理解它的意思。
这是我的完整代码。
api_Request.cs
public class api_Request
{
public RootObject GetApi(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
return serializer.Deserialize<RootObject>(jsonReader);
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
}
public class Buy
{
public int listings { get; set; }
public int unit_price { get; set; }
public int quantity { get; set; }
}
public class Sell
{
public int listings { get; set; }
public int unit_price { get; set; }
public int quantity { get; set; }
}
public class RootObject
{
public int id { get; set; }
public List<Buy> buys { get; set; }
public List<Sell> sells { get; set; }
}
Form1.cs
private void button1_Click(object sender, EventArgs e)
{
RootObject RootObject = new RootObject();
api_Request api_Request = new api_Request();
richTextBox1.Text = api_Request.GetApi("https://api.guildwars2.com/v2/commerce/listings").id.ToString();
}
在这个 json 中是一个单一的 ID,所以这个工作正常。 https://api.guildwars2.com/v2/commerce/listings/19684
但是像这里一样检索多个 ID 时,它会中断。
https://api.guildwars2.com/v2/commerce/listings
您为多个 ID return 提供的 link 整数数组。我建议这样解析:
var ids = JsonConvert.DeserializeObject<int[]>(jsonReader.ToString())
正如您所说,您的代码适用于单个项目,因此您可以将现有代码用于每个单独的请求,而不是点击 https://api.guildwars2.com/v2/commerce/listings
,而是点击 https://api.guildwars2.com/v2/commerce/listings/{id}
,您可以使用 string.Format()
在需要的地方添加。
认真考虑 int[]
中有多少个 id return 是你真正想要获取根对象的,据我所知,它是 returns ,你会提出很多请求。
这是一个简单的解决方案,可以获取所有 ID 的列表,但需要花费大量时间才能完成所有这些
List<RootObject> rootobject = new List<RootObject>();
using (var webclient = new WebClient())
{
var Ids = webclient.DownloadString(" https://api.guildwars2.com/v2/commerce/listings");
foreach (var id in Ids.Substring(1, s.Length-2).Split(','))
{
string url = string.Format("{0}/{1}","https://api.guildwars2.com/v2/commerce/listings",id);
var res = webclient.DownloadString(url);
var jsonObject = JsonConvert.DeserializeObject<RootObject>(res);
rootobject.Add(jsonObject);
}
}
我有这段代码可以从 API link 中检索 Json 字符串。 Json 被反序列化并 returned 到文本框。只要只有 1 个 Json 值,它就可以完美运行,returned 超过 1 个值时它会崩溃并出现此错误:
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'GW2_tradingPost.RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
我的研究之所以会发生这种情况,是因为 Json 不是列表,因此无处存放。
我试过这段代码和各种类似的代码。
List<RootObject> list = JsonConvert.DeserializeObject<List<RootObject>>(jsonReader.ToString());
return list;
这将 return 错误:
Error 1 Cannot implicitly convert type 'System.Collections.Generic.List' to 'GW2_tradingPost.RootObject' e:\mega\gw2_tradingpost\gw2_tradingpost\api_request.cs 34
我不完全理解它的意思。
这是我的完整代码。
api_Request.cs
public class api_Request
{
public RootObject GetApi(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
return serializer.Deserialize<RootObject>(jsonReader);
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
}
public class Buy
{
public int listings { get; set; }
public int unit_price { get; set; }
public int quantity { get; set; }
}
public class Sell
{
public int listings { get; set; }
public int unit_price { get; set; }
public int quantity { get; set; }
}
public class RootObject
{
public int id { get; set; }
public List<Buy> buys { get; set; }
public List<Sell> sells { get; set; }
}
Form1.cs
private void button1_Click(object sender, EventArgs e)
{
RootObject RootObject = new RootObject();
api_Request api_Request = new api_Request();
richTextBox1.Text = api_Request.GetApi("https://api.guildwars2.com/v2/commerce/listings").id.ToString();
}
在这个 json 中是一个单一的 ID,所以这个工作正常。 https://api.guildwars2.com/v2/commerce/listings/19684
但是像这里一样检索多个 ID 时,它会中断。 https://api.guildwars2.com/v2/commerce/listings
您为多个 ID return 提供的 link 整数数组。我建议这样解析:
var ids = JsonConvert.DeserializeObject<int[]>(jsonReader.ToString())
正如您所说,您的代码适用于单个项目,因此您可以将现有代码用于每个单独的请求,而不是点击 https://api.guildwars2.com/v2/commerce/listings
,而是点击 https://api.guildwars2.com/v2/commerce/listings/{id}
,您可以使用 string.Format()
在需要的地方添加。
认真考虑 int[]
中有多少个 id return 是你真正想要获取根对象的,据我所知,它是 returns ,你会提出很多请求。
这是一个简单的解决方案,可以获取所有 ID 的列表,但需要花费大量时间才能完成所有这些
List<RootObject> rootobject = new List<RootObject>();
using (var webclient = new WebClient())
{
var Ids = webclient.DownloadString(" https://api.guildwars2.com/v2/commerce/listings");
foreach (var id in Ids.Substring(1, s.Length-2).Split(','))
{
string url = string.Format("{0}/{1}","https://api.guildwars2.com/v2/commerce/listings",id);
var res = webclient.DownloadString(url);
var jsonObject = JsonConvert.DeserializeObject<RootObject>(res);
rootobject.Add(jsonObject);
}
}