9

I am trying to get RestSharp to work with a restful service that I have. Everything seems to be working fine, except when my object being passed via POST contains a list (in this particular case a list of string).

My object:

public class TestObj
{
    public string Name{get;set;}
    public List<string> Children{get;set;}
}

When this gets sent to the server the Children property gets sent as a string with the contents System.Collections.Generic.List`1[System.String].

This is how I am sending the object:

var client = new RestClient();
var request = new RestRequest("http://localhost", Method.PUT);

var test = new TestObj {Name = "Fred", Children = new List<string> {"Arthur", "Betty"}};
request.AddObject(test);
client.Execute<TestObj>(request);

Am I doing something wrong, or is this a bug in RestSharp? (If it makes a difference, I am using JSON, not XML.)

adrianbanks
  • 81,306
  • 22
  • 176
  • 206

3 Answers3

9

It depends on what server you're hitting, but if you're hitting an ASP.NET Web API controller (and probably other server-side technologies), it'll work if you add each item in the collection in a loop:

foreach (var child in test.Children) 
    request.AddParameter("children", x));
Rob
  • 26,989
  • 16
  • 82
  • 98
Josh Kodroff
  • 27,301
  • 27
  • 95
  • 148
  • 1
    I think this should be the top answer. There's no one proper way to get around this, and I personally think RestSharp should essentially employ this by default considering how prevalent IEnumerables are in web frameworks. Compared to other solutions I've seen on this post and on similar posts this solution can easily be encapsulated and relies on no external library (that likely introduces some overhead on each node in the collection). – deadboy Nov 02 '15 at 03:01
3

Use AddJsonBody

var client = new RestClient();
var request = new RestRequest("http://localhost", Method.PUT);
request.AddJsonBody(new TestObj {
     Name = "Fred", 
     Children = new List<string> {"Arthur", "Betty"}
});
client.Execute(request);

Api Side

[AcceptVerbs("PUT")]
string Portefeuille(TestObj obj)
{
    return String.Format("Sup' {0}, you have {1} nice children", 
        obj.Name, obj.Children.Count());
}
Julien G
  • 415
  • 1
  • 5
  • 20
  • Thanks for the answer @Koranger - would you know how the object would look in params - so it can be accessed in the server controller? – BenKoshy Jan 28 '17 at 07:33
2

I had a similar problem with a list of Guids. My post would work but the list would never have the correct data. I hacked it abit and used the json.net to serialize the object

Issue I had on another stackoverflow post

I know this isn't perfect but does the trick

Community
  • 1
  • 1
Diver Dan
  • 9,953
  • 22
  • 95
  • 166
  • I use JSON strings when dealing with IEnumerables in MVC viewmodels for what it's worth, so I don't think this is a bad solution at all. – Josh Kodroff Nov 03 '15 at 17:03