Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful partial request & partial serialization

I'd like to perform dynamic querying + partial serialization.

Let say I have a resource like this :

public class Unicorn
{
    public string Id { get; set; }
    public string Color { get; set; }
    public int Size { get; set; }
    public DateTime BirthDate { get; set; }
}

And a user make a partial RESTful request like this :

GET /unicorn/{id}/?fields=id,color

The result, if XML is requested should be :

<Unicorn>
  <Id>10</Id>
  <Color>Purple</Color>
</Unicorn>

And for Json

{"Unicorn":
  {"Id":10,
  "Color":"Purple"}
}

I'm currently working on the querying part (expression trees you are so powerful ^^)

But I have many options for the serialization part, none of which is of great satisfaction. As you can see, the serialized properties are specified dynamically, so attribute decoration is probably not the way to go.

What would you use and why ? I'll edit this post afterward to share your suggestions.

like image 227
Mose Avatar asked May 24 '26 00:05

Mose


1 Answers

Change your Unicorn class making sure you use nullables and tag the members with EmitDefaultValue = false:

   [DataContract]
   public class Unicorn {   

    [DataMember (EmitDefaultValue=false)] 
    public string Id { get; set; }     

    [DataMember (EmitDefaultValue=false)] 
    public string Color { get; set; }     

    [DataMember (EmitDefaultValue=false)] 
    public int? Size { get; set; }     

    [DataMember (EmitDefaultValue=false)] 
    public DateTime? BirthDate { get; set; } 
} 

Use dynamic LINQ to do your select see >> Dynamic LINQ example . I'm assuming you are doing a WCF REST application in which case this will be serialized according to your examples.

like image 128
Tommy Grovnes Avatar answered May 26 '26 14:05

Tommy Grovnes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!