我有一个用于将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到目前为止,我已经有了这个用于向JSON文件添加对象的Sub:
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中声明的那些讨厌的值。
另外,如果我想从JSON中获取某个id下的所有值,这种方法是否可行:
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非常感谢你的任何提示!
发布于 2019-09-18 13:34:25
未将.AtributeRaport分配给可能导致此问题的'attrlist‘
jsonroot.Add(New Rapoarte With {.Id = id, .AtributeRaport = (New List(Of AtributeRaport) From {
attrlist})})https://stackoverflow.com/questions/57985592
复制相似问题