首页 > 解决方案 > 在 JSON .NET 中将对象添加到 JSON

问题描述

我有一个用于将 JSON 映射到 C# 的简单类:

Public Class AtributeRaport
    Public Property NumeRaport As String
    Public Property ApplicationId As String
    Public Property ObjectId As String
    Public Property Selections As String
    Public Property Deprecated As String
End Class

Public Class Rapoarte
    Public Property Id As String
    Public Property AtributeRaport As List(Of AtributeRaport)
End Class

Sub到目前为止,我有这个用于将对象添加到 JSON 文件:

Sub AddToJson(id As String, nume As String, appId As String, objectId As String, selections As String, deprecated As String)
        Dim filePath = System.AppDomain.CurrentDomain.BaseDirectory & "\reports.json"
        Dim jsonData = IO.File.ReadAllText(filePath)
        Dim jsonroot As List(Of Rapoarte) = If(JsonConvert.DeserializeObject(Of List(Of Rapoarte))(jsonData), New List(Of Rapoarte))

        Dim attrlist = New AtributeRaport With {
            .ApplicationId = appId,
            .NumeRaport = nume,
            .ObjectId = objectId,
            .Selections = selections,
            .Deprecated = deprecated
            }
        jsonroot.Add(New Rapoarte With {.Id = id, .AtributeRaport = New List(Of AtributeRaport)})

        Dim serializerSettings As New JsonSerializerSettings
        serializerSettings.NullValueHandling = NullValueHandling.Ignore
        serializerSettings.Formatting = Formatting.Indented
        jsonData = JsonConvert.SerializeObject(jsonroot, serializerSettings)
        IO.File.WriteAllText(filePath, jsonData)
    End Sub

如果我运行它,输出是:

[
  {
    "Id": "1",
    "AtributeRaport": []
  }
]

对于我的生活,我不知道如何添加我在attrlist.

另外,如果我想id从 JSON 中获取某个特定下的所有值,这种方法是否有效:

Public Function GetAttributesJson(id As String, filepath As String) As List(Of String)
        Dim jObject As JObject = JObject.Load(New JsonTextReader(File.OpenText(filepath)))
        Dim attrlist As List(Of String) = New List(Of String)
        Dim resources As JArray = CType(jObject("id"), JArray)
        For Each attr In resources.Where(Function(obj) obj("id").Value(Of String) Is id.ToString)
            attrlist.Add(attr("ApplicationId").Value(Of String))
            attrlist.Add(attr("NumeRaport").Value(Of String))
            attrlist.Add(attr("ObjectId").Value(Of String))
            attrlist.Add(attr("Selections").Value(Of String))
            attrlist.Add(attr("Deprecated").Value(Of String))
        Next
        Return attrlist
    End Function

非常感谢您的任何提示!

标签: .netjsonvb.netfunctionclass

解决方案


.AtributeRaport分配给attrlist可能导致此问题的“”

  jsonroot.Add(New Rapoarte With {.Id = id, .AtributeRaport = (New List(Of AtributeRaport) From {
            attrlist})})

推荐阅读