我可以反序列化JSON匿名类型在C#? [英] Can I deserialize json to anonymous type in c#?

查看:136
本文介绍了我可以反序列化JSON匿名类型在C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从DB长JSON阅读。 我想是JSON的只是一个属性。

I read from the DB a long json. I want just one attribute of that json.

我有两个选择: 一个。创建了JSON接口和反序列化到该接口。    (它是一个矫枉过正,因为我只需要一个属性?) 湾找到我所需要的子字符串(正则表达式?)

I have got two options: a. Create an interface for that json and deserialize to that interface. (Is it an overkill as I need just one attribute ?) b. Find the substring I need (regex? )

哪一个是preferred?

which one is preferred ?

更新:我使用的是.NET 3.5

推荐答案

你为什么不反序列化使用 JSON.NET 的LINQ到JSON的方式( JObject 等),只问你需要通过name的值?

Why don't you deserialize using JSON.NET's "LINQ to JSON" approach (JObject etc) and just ask for the value you need by name?

这是足够动态的,所以你不必创建的一个接口的的一切,但它的很多比使用正则表达式不易碎。

That's sufficiently dynamic so you don't need to create an interface for everything, but it's a lot less brittle than using a regex.

JObject json = JObject.Parse(text);
JToken value = json["foo"]["bar"];

(我相信JSON.NET也是支持的动态在.NET 4中,但没有特别需要在这里使用它。)

(I believe JSON.NET also support's dynamic in .NET 4, but there's no particular need to use it here.)

这篇关于我可以反序列化JSON匿名类型在C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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