According to NewtonSoft's documentation, this code:
string props = "{\"lot\":\"TEST\",\"mhd\":\"2016-06-17\"}";
dynamic json = JsonConvert.DeserializeObject(props);
string s = json.mhd;
should work, but I get a RunTimeBinderException when I try it. I have Micrsoft.CSharp referenced and the compile works (it is a runtime error). I am compiling against .NET 4.0, using NewtonSoft version 7.
I tried accessing as json["mhd"], which works fine.
Am I missing something?
The json object is a JObject, so to get the value you need do:
string s = (string)json["mhd"];
I try this case in Newtonsoft.Json 3.5.8 version ,I get this error.
When I upgrade Newtonsoft.Json package version to 4.5.1 it works .
I think it has bug on older version.
#Candide pointed out what was wrong with your example, but if you still want to use json.mhd syntax and have real dynamic object to work with you can do it.
Try to deserialize it using the ExpandoObjectConverter:
var converter = new ExpandoObjectConverter();
dynamic json = JsonConvert.DeserializeObject<ExpandoObject>(props, converter);
Related
With Newtonsoft Json you can convert an object to a JObject by calling JObject.FromObject(object).
Is there a counterpart in System.Text.Json to get a JsonDocument from an object?
There is an open issue for it.
But now there is no such methods. You can try
using (JsonDocument document = JsonDocument.Parse(JsonSerializer.Serialize(object)))
{
...
}
One more issue
As of .NET 6.0 (comes with System.Text.Json 6.0.0), JsonSerializer.SerializeToDocument is available.
JsonDocument doc = JsonSerializer.SerializeToDocument(yourObject);
I have tried creating an adaptive card, parsing it from json. As mentioned in https://learn.microsoft.com/en-us/adaptive-cards/create/libraries/net#example-parse-from-json, I have installed AdaptiveCards package and tried using that function, but it throws a error like 'AdaptiveCard' does not contain a definition for 'FromJson'.
As there is a Breaking changes from v0.5:
Package renamed from Microsoft.AdaptiveCards to AdaptiveCards
It seems that you have installed Microsoft.AdaptiveCards but AdaptiveCards.
To install AdaptiveCards, please mark Include prerelease checkbox in NuGet package manager:
Apparently the documentation is outdated. The class is named AdaptiveCard now, without the last 's'.
So instead of:
var parseResult = AdaptiveCards.FromJson(card);
Use:
var parseResult = AdaptiveCard.FromJson(card);
I have the following code
var client = new HttpClient();
var url = new Uri("https://someuri/someresource", UriKind.Absolute);
var response = await client.GetAsync(url);
var content = await response.Content.ReadAsStringAsync();
var json = JsonConvert.DeserializeObject(content) as dynamic;
As per what I see when I debug the code, everything is completed successfully; i.e., the above returns the expected JSON, and json object has the expected properties... let's assume it is:
{ "current_page": 1, "total_pages": 7, "items": [ ... ] }
However, when I do json.current_page, I get the following exception:
'object' does not contain a definition for 'current_page' and no
extension method 'current_page' accepting a first argument of type
'object' could be found (are you missing a using directive or an
assembly reference?)
Does anyone has an ides on what's going wrong here?
P.S. I tried it with both types of Universal Apps, Windows 8.1 and Windows Phone 8.1.
P.S. Same code works with a Console application, but not Universal Apps.
You are getting an object with no defined properties on it and you need to parse it first. You can use System.Web.Helpers.Json class as follows
dynamic data = Json.Decode(json);
As I can see you are using newtonsoft so you can achieve the same using Parse as follows
dynamic d = JObject.Parse(#"{ ""current_page"": 1, ""total_pages"": 7}");
Console.WriteLine(d.current_page);
I recently ran into the same issue and saw that you had opened an issue on GitHub.
This is the answer:
UWP apps use the PCL259 assembly and it doesn't support dynamic. A dedicated assembly will probably be added in the future but not anytime in the next couple of releases.
- JamesNK
I am encountering a problem with Json.NET (version 6.0.5) that leaves me a bit puzzled.
One of my classes that gets to be serialized looks something like this:
[JsonConstructor]
public MyContainerClass(IEnumerable<AbstractBaseClass> myDerivedUnitClasses)
{
if (myDerivedUnitClasses == null)
{
Units = ImmutableHashSet.Create<object>();
}
else
{
Units = myDerivedUnitClasses.ToImmutableHashSet();
}
}
public IEnumerable<AbstractBaseClass> Units { get; private set; }
Using Json.Convert with TypeNameHandling set to TypeNameHandling.Auto serializes this without problems. The serialized JSON includes the expected $type-qualifier for the property: "System.Collections.Immutable.ImmutableHashSet`1[[AbstractBaseClass, MyLibrary]], System.Collections.Immutable"
I got one project in my Solution where I serialize the data structure and another one where I deserialize it using Json.Convert (deserialization also using automatic type name handling). Deserialization fails with this error: Error resolving type specified in JSON System.Collections.Immutable.ImmutableHashSet`1[[AbstractBaseClass, MyLibrary]], System.Collections.Immutable
Using the source of Json.NET I traced the error back to the DefaultSerializationBinder calling assembly.GetType(string name) and getting null as result.
So far so bad. Here comes the part that leaves me especially puzzled right now: When I deserialize the JSON in the same code block where I serialize my data structure everything works perfectly fine (using the same code that I use in the other project).
Thank you for your help.
Turns out there was an assembly binding problem regarding the assembly containing AbstractBaseClass in the one project. I used fuslogvw.exe of the Visual Studio Tools while debugging to check for errors and noted that the directories that were searched were not the ones I was expecting and did not contain the assembly file.
My solution was to subscribe to the AppDomain.CurrentDomain.AssemblyResolve-event prior to deserialization and then manually load the assembly from the correct path via Assembly.LoadFrom in the event handler.
I am using System.Web.Helpers.Json to deserialize some JSON into dynamic in NET 4. The following line fails with this error: TypeInitializationException: Attempt by method 'System.Web.Helpers.Json..cctor()' to access method 'System.Web.Helpers.Json.CreateSerializer()' failed.
var json = Json.Decode(response);
The response is lengthy but valid JSON. What could be the matter here? I have tried LINQPad with a short handcrafted JSON and it worked. Is this a configuration issue of some sort?
[EDIT]
Here is the actual sample JSON. It appears the content is pretty much irrelevant. When this is run in a brand new Console application or LINQPad, it works as expected. But if you try to run the same code from a brand new Windows Forms application, it barfs with the above error.
var json = Json.Decode("{\"r\":{\"0\":{\"id\":\"2\"},\"1\":{\"id\":\"33\"}}}");
[EDIT2]
Actually, it turns out this has nothing to do with project types. The exception is thrown if the project is being debugged. If it is simply run, the exception does not occur. Strange, eh?
I forgot about this question and I found my answer in the meantime. I think it was somewhere on Microsoft's Connect site but I am not sure. So let's share it now.
Basically, in order to workaround this problem you need to make sure "Enable the Visual Studio hosting process" is unchecked in your project's settings under Debug. I am not sure why it's happening but this is definitely a way to "fix" it. I stopped searching for answers once I found out about this. It was good enough for me.
This can also happen if you are running in a partial trust.
Check the exception description here for possible reasons.
I don't know if this will apply to you, since you are not running in a web context, but this is what that link describes:
This exception is thrown in situations such as the following:
A private, protected, or internal method that would not be accessible from normal compiled code is accessed from partially
trusted code by using reflection.
A security-critical method is accessed from transparent code.
The access level of a method in a class library has changed, and one or more assemblies that reference the library have not been
recompiled.
There is problem in the inbuilt json class.
If you want to achieve this in alternate way, please use the below code:
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new DynamicJavaScriptConverter[] { new DynamicJavaScriptConverter() });
var result = WrapObject(serializer.DeserializeObject(value)); // here you will have result.
private object WrapObject(object value)
{
IDictionary<string, object> values = value as IDictionary<string, object>;
if (values != null)
{
return new DynamicJsonObject(values);
}
object[] arrayValues = value as object[];
if (arrayValues != null)
{
return new DynamicJsonArray(arrayValues);
}
return value;
}
Further to Roland's answer: some assembly mismatches listed can be fixed in the AssemblyInfo.cs file.
The offending line in my AssemblyInfo was this:
[assembly: AllowPartiallyTrustedCallers]
Removing this allowed me to access the public property (on a public class) that I was trying to set from another assembly that had dynamically loaded this assembly.