我如何获得这部分JSON的一部分?

时间:2015-03-24 12:29:34

标签: json vb.net linq json.net

我知道与此非常相似的问题已经发布,但是JSON文件的结构都相当不同,虽然我对使用JSON和VB很新,但我更喜欢使用数据库,我已经做了一些时间和我通常做的不起作用。

我已经把每个数字项中的值拉出来,但是一旦我进入它,我在尝试使用image2.Value(“id”)时会出错。所以我可以访问正确的唯一方法是做一个If声明,如果image2.Name =“id”那么如果image2.Value()= strFigID然后做一些事情。

这是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

2 个答案:

答案 0 :(得分:2)

首先,正如已经指出的那样,这是无效的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字符串中的一个值。

答案 1 :(得分:1)

如果我是你,我会尝试使用类型结构来解析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似乎无效,需要{}大括号