使用Web Matrix助手进行C#JSON解码

Phi*_*hil 10 c# json

我一直在寻找一种将JSON对象转换为动态对象的简洁方法.

(我可以转换为一个对象,但Twitter Streaming API实际上发送了两个不同的JSON对象,可能有未来的对象类型!)

我目前使用的代码来自:

将JSON反序列化为C#动态对象?

但它不是最干净的代码而且我正在玩Web Matrix,并注意到他们有一个很好的JSON.Decode(字符串)和JSON.Encode(对象)方法,并希望利用它们.

http://msdn.microsoft.com/en-us/library/system.web.helpers.json(v=vs.99).aspx

将System.Web.Helpers的引用添加到我的C#控制台应用程序我设法编译一个调用JSON.Decode的解决方案但是...它引发了一个令人讨厌的异常.

这可能取决于我以非预期的方式使用它(在Web Matrix之外),但任何想法?可能期待一个简单的,没有那个愚蠢的回答;-)

尝试通过方法'System.Web.Helpers.Json.Decode(System.String)'访问字段'System.Web.Helpers.Json._serializer'失败.


我正在使用VS2010.

更多细节:System.FieldAccessException被方法'System.Web.Helpers.Json.Decode(System.String)'捕获Message = Attempt以访问字段'System.Web.Helpers.Json._serializer'失败.Source = System.Web.Helpers StackTrace:位于C:\ Users\Administrator\documents\visual studio 2010\Projects\ISMM的Components.DataCollection.ConvertTwitterStream.ConvertTweets()中的System.Web.Helpers.Json.Decode(String value)处\ Components\DataCollection\ConvertTwitterStream.cs:第35行InnerException:

小智 13

启用Visual Studio宿主进程(默认情况下)时,调试对'Json.Decode'的调用失败.我发现它可以在禁用托管进程或没有调试器的情况下运行.

可以按照以下说明为您的项目禁用托管过程:http: //msdn.microsoft.com/en-us/library/ms185330.aspx


mck*_*mey 5

为了支持jbtule的答案,JsonFx v2(http://github.com/jsonfx/jsonfx)让这很容易.下面的示例显示了完整的往返,其中动态对象是从JSON字符串构建的,然后序列化为JSON.

string input = "{ \"foo\": true, \"array\": [ 42, false, \"Hello!\", null ] }";
dynamic value = new JsonReader().Read(input);
// verify that it works
Console.WriteLine(value.foo); // true
Console.WriteLine(value.array[0]); // 42
Console.WriteLine(value.array.Length); // 4

string output = new JsonWriter().Write(value);
// verify that it works
Console.WriteLine(output); // {"foo":true,"array":[42,false,"Hello!",null]}
Run Code Online (Sandbox Code Playgroud)