ItJustWerks
ItJustWerks

Reputation: 581

Anonymous object blob in database not serializing as JSON when queried

I have a need to store an unknown data structure in a SQL Server database table field via ORMLite. This is to support a timeline feature on a website where each step on the timeline contains different information, and I want to store them as generic "Steps", with the variable data in a "StepData" property. I have the POCO set up like this:

public class ItemStep
{
    public ItemStep()
    {
        this.Complete = false;
    }

    [Alias("ItemStepId")]
    public Guid Id { get; set; }

    [References(typeof(Item))]
    public Guid ItemId { get; set; }
    [References(typeof(Step))]
    public int StepId { get; set; }
    public object StepData { get; set; }

    [Reference]
    public Step Step { get; set; }

    public bool Complete { get; set; }
    public DateTime? CompletedOn { get; set; }
}

My front-end send a JSON object for StepData, and it's saved to the database appropriately.

{itemAmount:1000,isRed:False,isBlue:True,conversion:True}

Now, when I go to retrieve that data using...

List<ItemStep> itemSteps = Db.Select<ItemStep>(q => q.ItemId == request.ItemId).OrderByDescending(q => q.StepId).ToList<ItemStep>();

...the "StepData" node of the JSON response on the client is not a Javascript Array object as I'm expecting. So, on the client (AngularJS app using Coffeescript),

ItemStep.getItemSteps(ItemId).then((response) ->
    $scope.StepData = response.data.itemSteps[0].stepData

is a double-quoted string of the JSON array.

"{itemAmount:1000,isRed:False,isBlue:True,conversion:True}"

Can anybody help me with this? I've tried parsing that string as JSON and I can't seem to get it to work:

JSON.parse($scope.StepData)

I'm using the exact same methodology in other areas of the app to store and retrieve things like addresses, with the only difference I can see being that there is a specified Address class.

Thanks!

Upvotes: 1

Views: 304

Answers (1)

ItJustWerks
ItJustWerks

Reputation: 581

Found this link that solved my problem: https://github.com/ServiceStackV3/mythz_blog/blob/master/pages/314.md

Essentially I added a "Type" field to the ItemStep class, and set that when I create a new row (create the next step in the timeline). Then, when I retrieve that record, I call a method like "GetBody" in the referenced link (GetStepData for me), that deserializes the object using the stored Type. I then stuff that back into a generic "object" type in the return POCO so that I can include many steps of varying types in the same call. Works great!

Thanks Mythz for the blog post!

Upvotes: 1

Related Questions