gpt4 book ai didi

json - 系统文本 Json 从对象数组中读取单个对象

转载 作者:行者123 更新时间:2023-12-05 06:23:24 24 4
gpt4 key购买 nike

我正在尝试使用新的系统文本 Json 库从我的 json 数组中读取单个对象。我的 json 看起来像这样:

[
{
"Id": "test1",
"Version": "16.0.461",
},
{
"Id": "test2",
"Version": "2.1.0",
}
]

这只是一个例子。一个 Json 对象实际上有大约 12 个属性。但是假设在 c# 中有一个类,它看起来像这样:

     public class Data
{
public string Id { set; get; }
public string Version { set; get; }
}

我只想获取 id 与给定名称匹配的包,我是这样尝试的:

    private static ObjectData GetSingleData(string jsonString, string objectName)
{
var options = new JsonDocumentOptions
{
AllowTrailingCommas = true
};

using (JsonDocument document = JsonDocument.Parse(jsonString, options))
{
ArrayEnumerator arrayEnumerator = document.RootElement.EnumerateArray();
//ObjectEnumerator objectEnumerator1 = document.RootElement.EnumerateObject();
while (arrayEnumerator.MoveNext())
{
JsonElement current = arrayEnumerator.Current;
if (objectName.Equals(current.GetProperty("id")))
{
//here the conversion from current to object should happen, but I don't know how
}
}
}

return null;
}

是否可以将 JsonElement 转换为我的Data 类的实例?

最佳答案

使用这样的东西:

JsonElement current = document.RootElement;  
if (objectName.Equals(current.GetProperty("Id")))
{
//But i'm using TryGetProperty
//This is example code for first element in JSON array
string id = current[0].GetProperty("Id").GetString(); //test1
string version = current[0].GetProperty("Version").GetString(); //16.0.461

//And now you can create your Data object
Data data_object = new Data(id, version)
}

如果我理解正确的话,这应该可以。

更新:我不建议你使用标准库,所以使用 Json.NET 代替,这个库非常方便并且工作速度更快(例如,我实现了反序列化速度到 ~0.2 秒 link for more info )

更新 2:
对于 .NET 5:

关于json - 系统文本 Json 从对象数组中读取单个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58390425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com