您如何使用System.Text.Json从json中读取一个简单值? [英] How do you read a simple value out of some json using System.Text.Json?

查看:1310
本文介绍了您如何使用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.

这篇关于您如何使用System.Text.Json从json中读取一个简单值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆