json.netswagger

Swagger create JSON result .NET


I am new in programming APIs. Currently I'm working with the SwaggerUI for .NET

I want to answer requests in the JSON-Format:

{
  "id": "value"
}

How can I create and return such a format for my values? For example, the default code in the project returns

[
    "value"
]

by using this function

public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

How can I return a JSON object which will be interpreted correctly by swagger?


Solution

  • You have the right setup for returning the object as needed. The problem is you aren't returning the right object.

    The expected json {"id":"value"} is a json representation of an object. The json that you are returning is a json representation of a list.

    The json you are returning is a list, because that is what your method is returning. As @NateBarbettini answered, you need to change what your method is returning.

    The value that your method is returning is string[] which is a string array, which will be formatted into a JSON list. You need to instead return an object. You can use an anonymous object like @NateBarbettini suggested, or you can return a custom class that you write.

    To produce the result, the class:

    public class FooViewModel 
    {
        public string Id {get; set;}
    }
    

    would do the trick.

    The problem you have now is the casing is off. FooViewModel.Id uses PascalCase, which is standard in C#, but json uses camelCase.

    1. You can break C# convention and use camelCase property names
    2. You can adjust your JsonSerialization Settings in Startup.cs or Global.asax.cs to use camelCase: config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); where config is your HttpConfiguration. You may see this in your code as GlobalConfiguration.Configuration
      1. CamelCasePropertyNamesContractResolver
      2. Configuring WebApi
    3. You can use the JsonPropertyAttribute to explicitly set what the json name of your property should be.

    Example

    [JsonProperty("id")]
    public string Id {get; set;}
    

    No matter what you do, you'll have to change the return type of your method from IEnumerable<string>. I like specifics, so I would set your return type to whatever you name your class, but leaving it at object would work just fine.