如何在 json.net 中找到具有多个值的字符串

How do you find a string in json.net that has mutiple values

我有 json 个文件

[{"a":"Value","b":"Value"},{"a":"Value1","b":"Value1"}]

我想找到 Value1 的 "a" 我该怎么做? (我不确定之前是否有人问过这个问题,但我不知道如何赞美这句话。

你的问题不是很清楚,但我想你的意思是你想在 JSON 数组中找到一个特定的对象,其中 a 属性 的值为 Value1。在那种情况下,您可以使用 Json.Net 的 LINQ-to-JSON API(JObjects 等)来查找它,如下所示:

Dim json As String = _
    "[{""a"":""Value"",""b"":""Value""},{""a"":""Value1"",""b"":""Value1""}]"

Dim array As JArray = JArray.Parse(json)

Dim obj As JObject = _ 
    array.FirstOrDefault(Function(jo As JObject) jo("a").ToString() = "Value1")

If obj Is Nothing Then
    Console.WriteLine("Not found")
Else
    Console.WriteLine("a: " & obj("a").ToString())
    Console.WriteLine("b: " & obj("b").ToString())
End If

您的问题不清楚,因为答案永远是 "a"。看实际数据:

[{"a":"3010828","b":"Jupiter Chair"},{"a":"3010829","b":"Saturn Chair"}...]

A 和 B 最好命名为 "ID" 和 "Item":ID“3010828”是 "Jupiter Chair"。

这会将 AB 对转换为字典,这将是一种更有用的单步执行方式。弄乱这些时,有助于查看内部结构。将 JSON 粘贴到像 http://jsonutils.com/ 这样的助手中 从那里,我们得到这个:

Public Class AB
    Public Property a As String
    Public Property b As String
End Class

它很容易反序列化为数组或列表。数组不是很有趣,因为它仍然有 A 和 B 粘在一起。这将使用上面 class 的列表并转换为字典,以便通过 ID:

轻松查找
Dim json As String = ' the long file

Dim jl As List(Of AB)
jl = JsonConvert.DeserializeObject(Of List(Of AB))(jstr)

Dim myCol As Dictionary(Of String, String) = jl.ToDictionary(
            Function(k) k.a,
            Function(k) k.b)

Console.WriteLine(myCol("5000074"))

输出:

Bing Monkey

List(Of AB) 非常好用,转换为字典可以更容易地从 ID 中获取项目。如果您真的 想通过项目或名称获取 ID,请反转上面的 k.ak.b。如果您真的只想要 43,000 多件商品中的一件,请参阅其他答案。


if i reverse k.a and k.b nothing happens ( i want the item id from item name)

它可能抛出了一个你没有捕捉到的异常。如果您深入查看列表,您会发现某些项目可以有多个 ID。这在字典中是非法的,并且尝试创建可搜索的容器毫无意义。

相反,将其保留为 List(Of AB) 并查询它以查找内容:

Dim findTxt As String = "Miho"
' get a list of all IDs (A) where B matches the above, case insensitive:
Dim miho = jl.Where(Function(x) x.b.ToLowerInvariant = 
      findTxt.ToLowerInvariant).Select(Function(m) m.a).ToList

' get all matches as into smaller List(of AB)
Dim AllMihoAB = jl.Where(Function(x) x.b.ToLowerInvariant =
                                      findTxt.ToLowerInvariant).ToList

' get just the first ID to match:
Dim FirstMihoA = jl.FirstOrDefault(Function(x) x.b.ToLowerInvariant =
             findTxt.ToLowerInvariant).a

我不知道你想怎么用它。