0

I want to return a result from a method in my ASP.NET MVC WebAPI application with the following signature:

public class Result
{
    public int ResultCode { get; set; }
    public MapFeatureViewModel Params { get; set; }
    public string Message { get; set; }
}

and the MapFeatureViewModel type signature is

public class MapFeatureViewModel
{
    public long Id { get; set; }
    public string Uuid { get; set; }
    public string Feature { get; set; }
    public long MapId { get; set; }
}

Everything works fine till now; but if I try to change the type of Params in Result class to "object" or "dynamic" in order to use it for all other methods I receive the following error message:

"You must write an attribute 'type'='object' after writing the attribute with local name '__type'."

Any idea how to make WebAPI serialize non-strongly typed properties?

tereško
  • 58,060
  • 25
  • 98
  • 150
Mahdi Taghizadeh
  • 903
  • 2
  • 10
  • 31
  • Generally, ASP.Net Web API uses strongly typed CLR objects as models, however you may deserialize JSON into C# dynamic object. – Yusubov Jun 13 '12 at 13:58

2 Answers2

0

The in-the-box formatters don't know how to deal with dynamics or object. You can however create a custom formatter (MediaTypeFormatter) that can write them out using custom logic. In the formatter add MediaTypeHeaderValue instances for "application/json" and "text/json" to the SupportedMediaTypes collection. You'll also want to override CanWriteType to limit the formatter to only work for the type you are serializing i.e. MapFeatureViewModel. You'll need to insert that formatter at the beginning of the collection so that it runs as opposed to the default formatter. You can do this by accessing the formatters collection on the configuration object.

Glenn Block
  • 8,463
  • 1
  • 32
  • 34
0

There are couple alternatives to consider. In Web API, you can use strongly typed CLR objects as models, and they will automatically be serialized to XML or JSON for the client. visit for more info

However, you may Deserialize JSON into C# dynamic object. How to do that, well there is a good post on this topic. visit for more info

Community
  • 1
  • 1
Yusubov
  • 5,815
  • 9
  • 32
  • 69