.net - 在 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
非常感谢您的任何提示!
解决方案
未.AtributeRaport
分配给attrlist
可能导致此问题的“”
jsonroot.Add(New Rapoarte With {.Id = id, .AtributeRaport = (New List(Of AtributeRaport) From {
attrlist})})
推荐阅读
- c# - 如何将其他列表绑定到其他 ItemsSource 中的 ItemsSource
- powershell - PowerShell ErrorRecord.CategoryInfo.Activity (CategoryActivity)
- html - 如何在新行中换行
- python - 如何在 pandas 数据框中的某个范围内对每第 n 行进行采样?
- python - 使用 Erlang C 求解调用次数
- python - 在 Python3 中使用大型机数据集
- automation - 单击多个窗口 - Hammerspoon 中的 AutoHotKey 等效项
- python - 具有插件层次结构的跨模块的 Python 日志记录
- sql - 更新一行以实现错误捕获
- react-native - npm 错误!代码 ENOTEMPTY npm 错误!尝试安装 Expo 以进行本机反应时重命名系统调用