I've been searching for a while for a nice and clean way to convert a JSON object to a dynamic object.
(I could cast to an object but the Twitter Streaming API actually sends two different JSON objects with the possibility of future object types!)
The code I use currently is from:
Deserialize JSON into C# dynamic object?
But its not the cleanest code and I was playing around with Web Matrix and noticed that they have a nice JSON.Decode(string) and JSON.Encode(object) methods and wanted to make use of them.
http://msdn.microsoft.com/en-us/library/system.web.helpers.json(v=vs.99).aspx
Adding a reference to System.Web.Helpers to my C# console application I managed to compile a solution calling JSON.Decode but... it throws a nasty exception.
This is probably down to me using it in a way not intended (outside Web Matrix) but any ideas? Probably expecting a simple, no thats silly answer ;-)
Attempt by method 'System.Web.Helpers.Json.Decode(System.String)' to access field 'System.Web.Helpers.Json._serializer' failed.
I'm using VS2010.
More detail:
System.FieldAccessException was caught
Message=Attempt by method 'System.Web.Helpers.Json.Decode(System.String)' to access field 'System.Web.Helpers.Json._serializer' failed.
Source=System.Web.Helpers
StackTrace:
at System.Web.Helpers.Json.Decode(String value)
at Components.DataCollection.ConvertTwitterStream.ConvertTweets() in C:\Users\Administrator\documents\visual studio 2010\Projects\ISMM\Components\DataCollection\ConvertTwitterStream.cs:line 35
InnerException:
Debugging calls to 'Json.Decode' fail when the Visual Studio hosting process is enabled (which is the default). I found it worked with the hosting process disabled or when running without the debugger.
The hosting process can be disabled for your project by following these instructions:
http://msdn.microsoft.com/en-us/library/ms185330.aspx
To support jbtule's answer, JsonFx v2 (http://github.com/jsonfx/jsonfx) makes this really easy. The example below shows a full round-trip with dynamic object being built from a JSON string and then serialized back into 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]}
JsonFx Supports several strategies of binding json to .net objects including dynamic objects.
https://github.com/jsonfx/jsonfx
I don't recall if Json.NET has support for dynamic objects yet, but it seems that you are able to do so with a little extra custom coding.
http://json.codeplex.com/
http://weblogs.asp.net/britchie/archive/2010/08/05/json-net-dynamic-extensions.aspx
Microsoft has added a Json helper class to Web Matrix Beta 2. Sample code here http://www.mikesdotnetting.com/Article/160/WebMatrix-Working-With-The-JSON-Helper
There seems to be a privileges issue when using Json.Decode in a Console App. Right-mouse click on your EXE and "Run as administrator..." and it should work.
I am not sure if there is a way to force Visual Studio to run the executable as administrator for debugging purposes or not.
Related
I'm building an app using Xamarin.Android and I've come across an issue where JSON.NET never finishes parsing. I've tried both the JsonConvert and JObject classes. Calling the parse methods never finishes. I added a breakpoint on the line that parses the string and one after it. The one after never hits.
What I've tried:
Other JSON libraries: no succes
Running the app on the device itself: no success
Not using the shared mono runtime: no success
Using an older version of JSON.NET: no success
I'm using the latest version of Xamarin.Android and JSON.NET that are available at this moment.
Does anyone know what I'm doing wrong or why this doesn't work? JSON Deserialization is very important for this app.
Thank you in advance
Alright, seems that I have figured it out. My input json was indeed the issue. I was trying to directly parse the input to an object, when the input json was an array with one single object in it. Parsing to a JArray worked fine right away.
Answering my own question just in case anyone hits the same issue and oversees the same thing :)
Turns out any input I tried had this same format of an array with one single object in it.
I started learning Pact via a tutorial that used a single .json file that tested a basic API interaction. Now I want to start organising my PACTs by splitting them into multiple JSON files.
When setting up the Pact Verifier is there a way to specify the PactUri as a folder path rather than a path to a JSON?
This is what my verifier looked like originally:
IPactVerifier pactVerifier = new PactVerifier(config);
pactVerifier.ProviderState($"{_pactServiceUri}/provider-states")
.ServiceProvider("Provider", _providerUri)
.HonoursPactWith("Consumer")
.PactUri(#"..\..\..\..\pacts\my-single-pact.json")
.Verify();
I understand that the following cannot work as the PactUri() expects a file uri.
.PactUri(#"..\..\..\..\pacts")
.PactUri(#"..\..\..\..\pacts\*.json")
I asked the same question at the Pact forum in Github. This feature is supported by the underlying CLI but it's not offered in PactNet.
I've been developing a game and part of the process was going to be a custom level tool and file format. I had created a small console application that generated a 'LevelAsset' object which contained only primative data types. The problem arises when I try to deserialize that data within my unity game. I didn't copy any code from my console app and rewrote both the 'LevelAsset' object and Deserialization code from scratch. Yet when I run the game, I get an error saying I'm missing the "Level Tool, version=1.0.0.0" assembly, which is from my original console app. How is this occuring. Is the binary serializer encoding information about the project?
Edit: So upon further investigation it appears that the BinnaryFormatter does indeed include information about the project in the form of a file header. So my new question is now: How on earth do I serialize without headers?
So after a bit of digging its fairly obvious whats happening. BinaryFormatter does indeed encode project information in its file headers. If you want to avoid this you should use binary writer instead.
in my project i have some sort of level builder that create a new text file and save all my wanted data as readable json string in 1 line.
while the project run in web build or in unity it self i can read the levels from that text file and every thing working great, in mobile builds that doesn't work.
my question is:
is there a way to create or add lines to a class at runtime?
for example write a new string in the class at run time that will stay there after run time is over?
No, there isn't. At least not at mobile platforms.
But you should be able to parse JSON on mobile platforms if you set the Api Compatibility Level to .Net 2.0, not .Net 2.0 Subset and disable Strip Engine Code in the Player Setting.
As #Tijmen said there is no way to change a C# class at runtime. But I see no reason to do so. Instead you should change the JSON string, write it to the file and recreate the level instance.
Looking at your code reveals that you are writing to Application.dataPath which is not writable in iOS player. So it should work when your are using Application.persistentDataPath.
Further on I would refrain from calling the folder Resources as this has a special meaning in Unity.
No there isn't, but you can make an ArrayList instead and put the info from the text file into the ArrayList. Then extract information from the ArrayList.
I have a basic messaging application that takes requests from clients and returns them response objects. When I encounter a malformed request object I serialize it to a database log for failed requests in a binary field. I'd like to be able to deserialize these malformed request objects and inspect them after the fact.
Is there a way to use the Visual Studio Watch window (or something like it) in my own app? I'm aware of the property grid and that's what I'm using for now but it'd be cool to use the watch window to inspect the objects since the watch window is what most of the developers are familiar with.
How about using Visual Studio itself? You already know how to serialize (and so I presume deserialize) the object. Why not write an app to deserialize it and then hook up the VS debugger to that app?
I would use the PropertyGrid control. It can be used to inspect a single object at a time.
What is it that you prefer in the Watch Window over the property grid? Is it the ability to evaluate custom expression, or just it's UI?
If it is the former, then,
I don't know anything out of the box that will let you do this, the thing that comes the closest (without attaching a debugger) is Crack.NET (see this picture), and you could theoretically incorporate that script window into your own project (it's open source, after all), but then you'd have to write your expressions in Python, not C#.
As for a more do-it-yourself approach, you could use CodeDom to compile your expression into a method that looks like:
object Evaluate(RequestObject request)
{
return ... your expression goes here ... ;
}
And then load the DLL you have automatically compiled to dynamically call this method, and then present its return value in the property grid if you like.