LocustHorde
LocustHorde

Reputation: 6409

Serializing and deserializing Entity Framework version

I have a model in my db that has versions, when I GET the object the C# version is a byte[8] but in Json, the object appears to be a string: AAAAAAAACXc= to be precise.

When I do a POST from my js app, my controller accepts a dynamic c# object because the data can be of any of derived classes and I need to be able to deal with all objects.

Currently, I'm doing this to deserialize object :

... Post([FromBody]dynamic data)
{
    var jsonObj = JsonConvert.DeserializeObject(data.ToString());

    //This line errors out
    CareTaker careTaker = JavaScriptSerializer().Deserialize<CareTaker>(jsonObj.ToString());
}

But I get an error:

exceptionMessage: "Cannot convert object of type 'System.String' to type 'System.Byte[]'"

because in CareTaker class, the Version property is defined as a byte[] but the json string appears asAAAAAAAACXc=..

How do I convert this version string into it's original format of: [0 0 0 0 0 0 9 119] ?

Thank you.

I thought I'd manually override this dynamic property value to byte array, so going this route. I've tried converting the string to normal byte array, but it seems to be more than 8 in length, end EF throws validation error saying that it should either be a string or a byte[] of length 8...

Upvotes: 0

Views: 1249

Answers (1)

Gusman
Gusman

Reputation: 15161

You're breaking all mixing JsonConvert and JavaScriptSerializer.

First, instead of deserialize/serialize/deserialize, why don't you use a JToken?

var token = JToken.Parse(data.ToString());

In this way you have an object like a collection where you can access members and check which type is.

And in this way you can then do

var deserObj = token.ToObject<theType>();

This will also correct the byte[] problem you have as Json.net will see that the property is a byte array and the data is a base64 string, it will take care of converting the data.

Upvotes: 1

Related Questions