[英]How do I parse this JSON data in C# and would it be more benefical to simply switch over to javascript?
我正在尋找解析這個 JSON 而我除了問題什么都沒有。 JSON 的鏈接在這里。 我正在嘗試訪問“href”字段。 在寫這篇文章時,我意識到數據字段實際上是一個數組,所以這是我的問題的一部分。
class Program
{
static void Main(string[] args)
{
var json = System.IO.File.ReadAllText(@"C:\Users\...\file.json");
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(json);
var x = myDeserializedClass.result.extractorData.data;
Console.Write(x.ToString());
}
public class Newcolumn
{
public string text { get; set; }
public string xpath { get; set; }
public string href { get; set; }
public string filepath { get; set; }
public string fileMimeType { get; set; }
public int fileTotalBytes { get; set; }
public string fileLastModifiedTime { get; set; }
}
public class Group
{
public List<Newcolumn> Newcolumn { get; set; }
}
public class Datum
{
public List<Group> group { get; set; }
}
public class ExtractorData
{
public string url { get; set; }
public List<Datum> data { get; set; }
}
public class PageData
{
public int statusCode { get; set; }
public long timestamp { get; set; }
}
public class Inputs
{
public string _url { get; set; }
}
public class Result
{
public ExtractorData extractorData { get; set; }
public PageData pageData { get; set; }
public Inputs inputs { get; set; }
public string taskId { get; set; }
public long timestamp { get; set; }
public int sequenceNumber { get; set; }
}
public class Root
{
public string url { get; set; }
public Result result { get; set; }
}
}
This ends up returning: System.Collections.Generic.List`1[ConsoleApp3.Datum]
我注意到字段名稱數據實際上變成了一個數組,盡管我不確定如何構造它。 data.[0].new Column.[0].group.etc... 顯然不起作用。 “新列”字段中的空格也有問題。 此外,當我調試並查看 JSON 查看器時,“新列字段為 null。我還嘗試了以下代碼:
public static void Main()
{
var json = System.IO.File.ReadAllText(@"C:\Users\...\file.json");
dynamic stuff = JsonConvert.DeserializeObject(json);
var a = stuff.result.extractorData.data;
string b = a.ToString();
Console.WriteLine(b);
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
這實際上確實返回了數據字段 object 但是,如果我執行 stuff.result.extractorData.data.group; 我明白了:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
HResult=0x80131500
Message='Newtonsoft.Json.Linq.JArray' does not contain a definition for 'group'
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
我認為這可能是因為數據字段中包含的數組,無論“新列”字段也是此方法的問題,因為空間。
在你上面的代碼中
public class ExtractorData
{
public string url { get; set; }
public List<Datum> data { get; set; }
}
其中 data 是 List 並且您嘗試以字符串形式訪問
Console.Write(x.ToString());
在數據變量 Datum 中是列表(您的變量有多個數據),並且在每個元素中都有一個列表。 (此 JSON 中應用的嵌套列表概念)
嘗試在下面的行添加斷點並逐行檢查代碼的執行。
var a = stuff.result.extractorData.data;
查看您的 JSON 文件圖像后,嘗試此代碼
Console.Write(a.FirstOrDefault()?.group.FirstOrDefault()?.Newcolumn.FirstOrDefault()?.href);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.