您如何使用System.Text.Json从json中读取一个简单值?
我有这个json
{"id":"48e86841-f62c-42c9-ae20-b54ba8c35d6d"}
我如何获得 48e86841-f62c-42c9-ae20-b54ba8c35d6d
出来吗?我可以找到的所有示例都显示出可以执行类似的操作
How do I get the 48e86841-f62c-42c9-ae20-b54ba8c35d6d
out of it? All examples I can find show to do something like
var o = System.Text.Json.JsonSerializer.Deserialize<some-type>(json);
o.id // <- here's the ID!
但是我没有适合这个定义的类型,我不想创建一个。我尝试过反序列化为动态,但是无法正常工作。
But I don't have a type that fits this definition and I don't want to create one. I've tried deserializing to dynamic but I was unable to get that working.
var result = System.Text.Json.JsonSerializer.Deserialize<dynamic>(json);
result.id // <-- An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Linq.Expressions.dll but was not handled in user code: ''System.Text.Json.JsonElement' does not contain a definition for 'id''
的定义?有人可以提出任何建议吗?
Can anyone give any suggestions?
编辑:
我刚刚发现我可以这样做:
I just figured out I can do this:
Guid id = System.Text.Json.JsonDocument.Parse(json).RootElement.GetProperty("id").GetGuid();
这确实有效,但是有更好的方法吗?
This does work - but is there a better way?
您可以反序列化为字典
:
var dict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, string>>(json)
或者只是反序列化为 Object
,这将产生一个 JsonElement
可以调用> code> GetProperty 。
Or just deserialize to Object
which will yield a JsonElement
that you can call GetProperty
on.