Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Swagger to C# object [duplicate]

Tags:

json

c#

Is there an easy way to convert Json string to C# object?

I have a swagger file in json format and need to make it to C# object

{
  "swagger": "2.0",
  "info": {
    "version": "Profiles",
    "title": "Profiles"
  },
  "paths": {
    "/api/Profiles/Get": {
      "get": {
        "tags": [ "Profiles"],
        "operationId": "Profiles_GetById",
        "consumes": [],
        "produces": [],
        "parameters": [{ "name": "id"}]
      }
    },
    "/api/Profiles": {
      "get": {
        "tags": [
          "Profiles"
        ],
        "operationId": "Profiles_GetBySubscriptionid",
        "consumes": [],
        "produces": [],
        "parameters": [{ "name": "subscriptionId"}]
      }
    }
  },
  "definitions": {}
}

So the problem that I am facing right now is that I have no idea how to convert paths to properties of my C# object. Specifically, I have no clue how I define a C# object properties for "/api/Profiles/Get", or "/api/Profiles".

public class SwaggerObject
{
  [JsonProperty("paths")]
  public SwaggerPath Paths { get; set;}
}
public class SwaggerPath {
  ... 
}
like image 247
Jihn Ta Avatar asked Jul 11 '17 19:07

Jihn Ta


People also ask

Is Swagger a JSON or YAML?

Swagger definitions can be written in JSON or YAML. In this guide, we only use YAML examples, but JSON works equally well. A sample Swagger specification written in YAML looks like: swagger: "2.0"

How does Swagger generate Client code?

Method 1: Use the swagger editor Alternatively you can select File , Import File and upload the downloaded swagger. json file. Next select Generate client and choose the language of your choice. The end result is a zip file you can download with the generated client code.

How can I get YAML file from Swagger UI?

If you don't see the url or if url is a code expression, open the browser dev tools, switch to the Network tab and disable caching. Then refresh the page and search for the API definition file ( swagger. json , swagger. yaml , api-docs or similar) among HTTP requests.


1 Answers

If you have a valid swagger definition, you can use AutoRest to generate a client for you. The auto-generated client includes models for all of the types you define in your swagger document.

You can then call Newtonsoft.Json.JsonConvert.DeserializeObject<MyModel>(json​) after you retrieve the response. Better yet, you can you the auto generated client to make the HTTP calls in your .NET code.

like image 58
Babak Naffas Avatar answered Oct 23 '22 01:10

Babak Naffas