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

查看:57
本文介绍了你如何使用 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''

谁能给点建议?

我刚刚发现我可以做到这一点:

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?

推荐答案

你可以反序列化为Dictionary:

var dict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, string>>(json)

或者只是反序列化为 Object 这将产生一个 JsonElement,您可以调用它 GetProperty on.

Or just deserialize to Object which will yield a JsonElement that you can call GetProperty on.

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

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