在我的JSON文件中,有一个数组(租金)。在此数组中,有一个变量,序列,可以为null或字符串。如果串行变量为null,我想遍历数组(租金),我想继续循环,但是当它不为null时,我想保存它。但是它不以这种方式表现。当获得“序列”时,数组停止循环。
这是我的代码:
public static string sendRequest(string url, string method) {
try
{
// Set reqiued information for api
var httpWebRequest = (HttpWebRequest)WebRequest.Create(main_url + url);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Headers.Add("Authorization", "Bearer " + Current_Access_Token);
httpWebRequest.Accept = "application/json;v=1";
httpWebRequest.Method = method;
// Get adn return responses
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string respStr = new StreamReader(httpResponse.GetResponseStream()).ReadToEnd();
return respStr;
}
catch (Exception e)
{
MessageBox.Show("No responses");
}
return "";
}
public static void GetRentGames()
{
string resp = sendRequest("api.php/currentCustomer/rents", "GET");
JObject jObject = JObject.Parse(resp);
JArray Juser = (JArray)jObject["response"]["data"]["rents"];
//Console.WriteLine(resp);
foreach(var i in Juser)
{
var matchGame = ApiConnector.rentGame.Find(x => x.name == i["item"]["name"].ToString());
if(matchGame == null)
{
//name and id works just fine. it is the serial i can't get, and I think because the serial is null?
Console.WriteLine(i["serial"].ToString());
var Game = new RentGame(i["item"]["name"].ToString(), i["id"].ToString(), i["serial"].ToString());
rentGame.Add(Game);
Console.WriteLine("Add rent game " + Game.name);
}
}
}
JSON文件-第一个索引:
"response":{
"code":200,
"status":"success",
"data":{
"rents":[
{
"id":"34414",
"start_date":"2015-12-08",
"download_url":null,
"serial":null, ...
要确定该值是否为空,请执行以下操作:
if(matchGame == null)
{
// Only do this if the serial is not null
if (i["serial"].Type != JTokenType.Null)
{
Console.WriteLine(i["serial"].ToString());
var Game = new RentGame(i["item"]["name"].ToString(), i["id"].ToString(), i["serial"].ToString());
rentGame.Add(Game);
Console.WriteLine("Add rent game " + Game.name);
}
困难在于,JSON解析器无法将JSON中的空对象转换为C#中的空对象。(为什么?!??)相反,它使它成为JToken对象,其“类型”为“空”。
您可以在调试器窗口中看到以下内容:“值”列显示为{},对我来说意义不大。“类型”列显示它是一个JToken对象。那么什么是JToken?好吧,如果展开,您会看到它具有很多属性:Next,Last,Parent,Path等...好的,这说明了为什么他们没有将其设置为真正的null。他们想跟踪所有其他这些东西。看起来您可以使用“ HasValues”属性或“ Type”属性来查看该事物是否为空。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句