6

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 {
  ... 
}
Jihn Ta
  • 61
  • 1
  • 1
  • 3
  • If you have a valid Json string I've used a Json converter to create a c# object. Example: Newtonsoft.Json.JsonConvert.DeserializeObject(Json); – Mickers Jul 11 '17 at 20:01
  • 2
    There is a builtin tool in Visual Studio to generate classes based on json file. Just copy the json and somewhere in 'View' you will find 'paste json as classes'. If you want to do this manually you can try using JsonProperty with 'api....' but not sure if it's gonna work. The other way is to deserialize it to Dictionary – MistyK Jul 11 '17 at 20:09
  • @Mickers In my Parser class, I already used JsonConvert.DeserializeObject(json). The problem is Json format is name-value pair; hence that I don't know how I should define the properties in the SwaggerPath so that it can contain "/api/Profiles/Get" or "/api/Profiles". – Jihn Ta Jul 11 '17 at 20:25
  • @MistyK , the internal visual studio tool is in Edit rather than in View. This is actually very useful and lovely. I had to go to websites every single time. – Olorunfemi Davis Aug 12 '20 at 18:45
  • If you want to convert swagger.json to object, microsoft.openapi.reader will be helpful – SpritZhou Dec 28 '22 at 03:15

1 Answers1

8

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.

Babak Naffas
  • 12,395
  • 3
  • 34
  • 49