相关疑难解决方法(0)

你如何使用 System.Text.Json 从一些 json 中读取一个简单的值?

我有这个 json

{"id":"48e86841-f62c-42c9-ae20-b54ba8c35d6d"}
Run Code Online (Sandbox Code Playgroud)

我如何48e86841-f62c-42c9-ae20-b54ba8c35d6d摆脱它?我能找到的所有例子都显示做类似的事情

var o = System.Text.Json.JsonSerializer.Deserialize<some-type>(json);
o.id // <- here's the ID!
Run Code Online (Sandbox Code Playgroud)

但是我没有符合这个定义的类型,我不想创建一个。我试过反序列化为动态,但我无法让它工作。

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''
Run Code Online (Sandbox Code Playgroud)

任何人都可以提供任何建议吗?


编辑:

我刚刚发现我可以这样做:

Guid id = System.Text.Json.JsonDocument.Parse(json).RootElement.GetProperty("id").GetGuid();
Run Code Online (Sandbox Code Playgroud)

这确实有效 - 但有更好的方法吗?

c# .net-core system.text.json

39
推荐指数
4
解决办法
3万
查看次数

标签 统计

.net-core ×1

c# ×1

system.text.json ×1