【问题标题】:deserialize JSON without one by one, multiple properties反序列化 JSON 无需一一多属性
【发布时间】:2018-01-07 18:51:30
【问题描述】:

我有这个 JSON:

{"JOE":{"id":7,"age":"23"},"BILLY":{"id":8,"age":"29"}}

我有this solution for a more simple JSON structure posted by RajN

Dim j1 As String = "{ "JOE"":""0.90000000"",""JOE"":""3.30000000"",""MONROE"":""1.20000000""}"
Dim dict = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(j1)
For Each kvp In dict
    Console.WriteLine(kvp.Key & " - " + kvp.Value)
Next

我正在寻找如何处理新的 JSON 数据。 提前致谢

【问题讨论】:

  • 现在你需要一个类来保存多位数据。您应该对使用 JSON 进行一些研究,这样您就不必一遍又一遍地问同样的问题,只有很小的变化
  • We both know thats not true 而是您有不了解您所获得的内容(然后猛烈抨击)的历史。再一次,没有人阻止你——如果你想存储更多的数据,你将需要一个类来保存它们。现在,愿 Google 与您同在。

标签: json vb.net json.net


【解决方案1】:

解决方案与@RajN 的the other solution you linked 几乎相同,除了您需要使用Dictionary(Of String, T) 而不是使用Dictionary(Of String, String),其中T 是您定义的用于保存id 和@987654327 的类@。

所以,定义一个类:

Public Class PersonData
    Public Property id As Integer
    Public Property age As String
End Class

然后反序列化:

Dim json As String = "{""JOE"":{""id"":7,""age"":""23""},""BILLY"":{""id"":8,""age"":""29""}}"

Dim dict = JsonConvert.DeserializeObject(Of Dictionary(Of String, PersonData))(json)

For Each kvp In dict
    Console.WriteLine("name: " & kvp.Key)
    Console.WriteLine("id: " & kvp.Value.id)
    Console.WriteLine("age: " & kvp.Value.age)
    Console.WriteLine()
Next

小提琴:https://dotnetfiddle.net/HMv7Om

有意义吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 2022-09-26
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多