如何使用反序列化到JSON.Net匿名类型? [英] How to deserialize using JSON.Net to an anonymous type?

查看:151
本文介绍了如何使用反序列化到JSON.Net匿名类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想在不知道参数提前任何创建JSON匿名类型,充分解释他们(可能有提示)。即该值看起来像一个int,字符串或日期。



这是我目前所知的唯一方法是创建一个有前一个匿名类型的知识。请参阅下面的.DeserializeAnonymousType(...)方法。



任何人都可以做的比这更好的?谢谢



  VAR jsonString ={\user_id\:1,\user_type\:\\ \\moderator\,\name\:\Fred\}; 

JToken根= JObject.Parse(jsonString);

变种anonTemplate =新的{USER_ID = 0,USER_TYPE =NAME =};

VAR一个= JsonConvert.DeserializeAnonymousType(root.ToString(),anonTemplate);


变种B = JsonConvert.DeserializeObject&所述;对象>(root.ToString()); //实际上变成一个JSONObject这是一件好事differet。






更新



我下载dynamicduck和我与它一点点打。将这个奇怪动态的包装Brian的理念是在-able我需要(序列化等)的方法是什么?



http://weblogs.asp.net/britchie/archive/2010/08/05/json-net-dynamic-extensions.aspx



http://weblogs.asp.net/britchie/archive/2010/08/03/dynamicduck-duck-typing-in-a-dynamic-world.aspx

解决方案

您可以用JSON.NET反序列化到的 ExpandoObject 使用的 ExpandoObjectConverter



要在运行时创建一个匿名类型,其相当多的复杂的,看看箍通过跳了在这个线程:



如何在其中创建LINQ表达式树与匿名类型


>你可以看到相当多的努力,可能是不值得的,因为你仍然不会得到任何编译时的安全性。所以href=\"http://msdn.microsoft.com/en-us/library/vstudio/dd264741.aspx\" rel=\"nofollow\">一个或ExpandoObject是你最好的赌注。


Just trying to create an anonymous type from JSON without knowing anything about the parameters ahead of time, and fully interpreting them (possibly with hints). i.e. that value "looks" like an int, string, or date.

The only way that I know of so far is to create an anonymous type that you have pre-knowledge of. See the .DeserializeAnonymousType(...) method below.

Can anyone do better than this? Thanks.

        var jsonString = "{\"user_id\": 1, \"user_type\": \"moderator\", \"name\": \"Fred\"}";

        JToken root = JObject.Parse(jsonString);

        var anonTemplate = new{user_id=0, user_type="", name="" };

        var a = JsonConvert.DeserializeAnonymousType(root.ToString(), anonTemplate);


        var b = JsonConvert.DeserializeObject<Object>(root.ToString());  // actually turns into a JsonObject which is something differet.


Update

I downloaded dynamicduck and am playing with it a little. Will this weird dynamic "wrapper" idea of Brian's be -able in the ways I need (serializable, etc)?

http://weblogs.asp.net/britchie/archive/2010/08/05/json-net-dynamic-extensions.aspx

http://weblogs.asp.net/britchie/archive/2010/08/03/dynamicduck-duck-typing-in-a-dynamic-world.aspx

解决方案

You can deserialize with JSON.NET to an ExpandoObject using the ExpandoObjectConverter.

To create an anonymous type at runtime, its quite a bit more complicated, take a look at the hoops jumped through in this thread:

How to create LINQ Expression Tree with anonymous type in it

As you can see quite a bit of effort that probably is not worth it as you still wouldn't get any compile time safety. So a dynamic or ExpandoObject are your best bets.

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

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