Your dynamic object has to implement the GetDynamicFieldNames() method properly for dynamic serialization to work.
Serializing a dynamic property to JSON
-
09-03-2022 - |
Pergunta
I have a Web API project that hydrates an object defined as the following from JSON. I am attempting to insert this object into a RavenDB database, but am finding that the dynamic property 'Content' is not being serialized properly (note the empty arrays).
I have tried several serializers to produce json strins: System.Helpers.Json.Encode(), System.Web.Script.Serialization.JavaScriptSerializer. Both suffers from the same problem.
RavenJObject.fromObject(obj) suffers from the same problem.
Is there a way to accomplish what I aim to do in spite of this apparent limitation in CLR reflection?
public class SampleType
{
public Guid? Id { get; private set; }
public dynamic Content { get; set; }
public string Message { get; set; }
public string Actor { get; set; }
public LogEntry()
{
Id = Guid.NewGuid();
}
}
JSON submitted to API:
{
"Content": {
"SomeNumber": 5,
"ADate": "/Date(1360640329155)/",
"MaybeABoolean": true,
"EmptyGUID": "00000000-0000-0000-0000-000000000000"
},
"Message": "Hey there",
"Actor": "John Dow"
}
Hydrated object:
ID: {b75d9134-2fd9-4c89-90f7-a814fa2f244d}
Content: {
"SomeNumber": 5,
"ADate": "2013-02-12T04:37:44.029Z",
"MaybeABoolean": true,
"EmptyGUID": "00000000-0000-0000-0000-000000000000"
}
Message: "Hey there",
Actor: "John Dow"
JSON from all three methods:
{
"Id": "b75d9134-2fd9-4c89-90f7-a814fa2f244d",
"Content": [
[
[]
],
[
[]
],
[
[]
],
[
[]
]
],
"Message": "Hey there",
"Actor": "John Dow"
}
Solução 2
Outras dicas
As I remember we used the Newtonsoft JSON serializer, it was handled dynamic and Expando objects well.
You can use Planet's fastest library for this Servicestack.Text
. The solution to your problem is already answered here.
I'm really not sure what you're getting at.
public class Foo
{
public dynamic Bar { get; set; }
}
var foo = new Foo { Bar = new { A = 1, B = "abc", C = true } };
Debug.WriteLine(RavenJObject.FromObject(foo).ToString(Formatting.None));
Debug.WriteLine(JsonConvert.SerializeObject(foo, Formatting.None));
Output of both of these is:
{"Bar":{"A":1,"B":"abc","C":true}}
Did I miss something?