0

I am generating C# classes from Swagger exposed model. For now, I am using the provided petstore example

http://petstore.swagger.wordnik.com/api/api-docs/pet

The Json from this url contains the following:

"category": {
    "$ref": "Category"
},

I tried to read this with Json.net by

[JsonProperty("$ref")]
public string Ref { get; set; }

My purpose is to instanciate Swagger Object model thanks to Json.net, then to use it to generate the swagger-described model.

It does not work and the object that holds this property remains null with no further exception (Also tries to set IsReference = true). It works when there is no $ref.

What would be the best practice to handle this cleanly?

remio
  • 1,242
  • 2
  • 15
  • 36

2 Answers2

3

The $ref is not intended to deserialized directly to a property value. In this case, it is indicating that a reference to an object defined elsewhere in the JSON named "Category" should be referenced.

For specific handling of $ref in JSON.NET see the section on PreserveReferencesHandling at http://james.newtonking.com/json/help/index.html?topic=html/PreserveObjectReferences.htm

Mike Hixson
  • 5,071
  • 1
  • 19
  • 24
  • I understand that. Hence, I removed my `Ref`property, I provided `new JsonSerializerSettings{PreserveReferencesHandling = PreserveReferencesHandling.Objects}` to `JsonConvert.DeserializeObject` from my understanding of the documentation... and I get the same result. In my objects structure, the referenced one is the third of an array, and remains `null` while its instance occurs later in the Json stream. Other objects in the array are deserialized properly. Having the reference name in a property would be more comfortable for my further usage, but I am also looking for a good practice! – remio Jul 18 '14 at 08:44
  • I think the example from JSON.NET shows the best practice. Basically, the $ref should be replaced the deserialized Category. – Mike Hixson Jul 18 '14 at 17:38
  • And this is my current issue. Instead of getting the deserialized Category, I get `null`. – remio Jul 19 '14 at 20:18
2

I had the exact same problem with the JSON Schema reference handling in Json.NET.

This is why I wrote my own JSON Schema parser, validator and generator: NJsonSchema. Based on this library, I implemented Swagger tools which correctly handle schema references: NSwag.

Maybe one of these libraries or tools help you solve your problem...

Rico Suter
  • 11,548
  • 6
  • 67
  • 93