我如何得到这个 JSON 的一部分?

How do I get part of this JSON out?

我知道已经发布了与此非常相似的问题,但是 JSON 文件的结构都非常不同,虽然我对 JSON 和 VB 的使用还很陌生,我宁愿使用数据库,我已经做了几次,但我通常做的是行不通的。

我已经认真地从每个数字数组项中提取值,但是一旦我进入它,我在尝试使用 image2.Value("id") 时遇到错误。所以我可以访问正确的唯一方法是做一个 If 语句说如果 image2.Name = "id" Then If image2.Value() = strFigID Then do something.

这是 JSON 的一部分。有效,这只是我提取的一部分,而不是整个 JSON 文件。

"figures":[
        {
            "id":"F001",
            "title":"Figure 1.  Some Figure",
            "sheets":[
                "1047815_01.gif",
                "1057923_02.gif"
            ]
        },
        {
            "id":"F002",
            "title":"Figure 2.  Another Figure",
            "sheets":[
                "f110__2184_00.gif"
            ]
        }
]

这是代码

If image.Name = "figures" Then
    Dim testingJArray As JArray = image.Value()
    For Each ArrayImage In testingJArray
        Dim jResults2 As JObject = JObject.Parse(ArrayImage.ToString())
        Dim imageResults2 As List(Of JToken) = jResults2.Children().ToList()
        Dim imageForLog2 As String = ""
        For Each image2 As JProperty In imageResults2
            imageForLog2 = image2.ToString()
            If image2.Name = "id" Then
                If image2.Value().ToString() = strFigID Then
                    ' ---------------------------------------------------
                    ' At this point I am at the correct Array Item
                    ' But now I need to get the array item out of
                    ' the sheets value
                    ' ---------------------------------------------------
                End If
            End If
        Next
    Next
End If

如果我是你,我会尝试使用类型结构来解析 JSON,像这样:

public class Figure
{
    public string id { get; set; }
    public string title { get; set; }
    public List<string> sheets { get; set; }
}

public class RootObject
{
    public List<Figure> figures { get; set; }
}

然后您可以简单地调用 JsonConvert.DeserializeObject<Figure> 来获取对象并使用 LINQ 找到您需要的任何东西

另外,你的JSON好像无效,需要{}个大括号

首先,如前所述,这是无效的 JSON。整个事情需要用“{ ... }”包裹起来。

获取数据的一种方法:

Dim js = JObject.Parse(jstr)

strGIF = js("figures")(0)("sheets")(0)   ' == 1047815_01.gif

定义 类 可能更容易使用:

Public Class Figure
    Public Property id As String
    Public Property title As String
    Public Property sheets As String()
End Class

Public Class FigsContainer
    Public Property figures As Figure()
End Class

要使用它们:

Dim figs = JsonConvert.DeserializeObject(Of FigsContainer)(jstr)

Dim s = figs.figures(0).sheets(0)   ' 1047815_01.gif again

类 是否值得取决于您是要处理数据还是只需要 json 字符串中的一个值。