Nix
Nix

Reputation: 58522

WEB.API returning string property as json

We have a fun situation where we are storing json as a string in SQL Server. We don't not care what is in this object its pretty much a passthrough property. Passthrough meaning we just save it for clients and return it as is. We never read it in C#. I'm storing it as a nvarchar in the database but I'm trying to figure out how i can automagically serialize that string into a json object to return to the client. I dont want to have to in javascript call fromJson.

We are using Newtonsoft as our Json Serializer. Here is the highlevel setup:

DTO:

public class MyDto{
    public  dynamic SessionBag { get;set;}
}

Entity Framework Entity:

public class My{
   public string SessionBag { get;set;}
}

A client would post/put us:

{"SessionBag":{"Name":"test"}}

We would then save it in the db as a string:

"{"Name":"test"}"

How can I serialize this so when it returns from Web.API it looks like:

{
   SessionBag:{
      Name: "test"
   }

}

I'm currently messing around trying to get it to save using dynamic / object. But i can't figure how how to return it as a json object. I would love to figure out how to do this with just annotations.

Here is how I convert it to a string to save:

 if (dto.SessionBag != null){
    var serializer = JsonSerializer.Create(new JsonSerializerSettings(){
                NullValueHandling = NullValueHandling.Ignore

    });
    using (var writer = new StringWriter()){
          serializer.Serialize(writer, dto.SessionBag);
          entity.SessionData = writer.ToString();
    }
 }

In case its helpful our WebApiControllers are pretty simple and just return an IHttpActionResult with the dto. All feedback is welcome.

Upvotes: 0

Views: 903

Answers (1)

Nix
Nix

Reputation: 58522

So I think i figured it out. In my dto:

[JsonIgnore]
public string  SessionBagString { get; set; }

public JObject SessionBag
{
        get
        {
            if (!string.IsNullOrEmpty(SessionBagString))
            {
                return JObject.Parse(SessionBagString);
            }
            return null;
        }
        set
        {
            if(value != null)
            {
                SessionBagString = value.ToString();
            }
        }
}

In my repo code I now have:

if (dto.SessionBag != null)
{          
  entity.SessionBagString =  dto.SessionBagString;
}

That pretty much worked for me. Let me know if there is a better way to do it.

Upvotes: 1

Related Questions