0

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"
}
ebpa
  • 1,171
  • 1
  • 12
  • 31

4 Answers4

2

As I remember we used the Newtonsoft JSON serializer, it was handled dynamic and Expando objects well.

Alex G.P.
  • 9,609
  • 6
  • 46
  • 81
0

You can use Planet's fastest library for this Servicestack.Text. The solution to your problem is already answered here.

Community
  • 1
  • 1
Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79
0

Your dynamic object has to implement the GetDynamicFieldNames() method properly for dynamic serialization to work.

Ayende Rahien
  • 22,925
  • 1
  • 36
  • 41
0

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?

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575