1

Here's a sample that's close to what I'm trying to do:

void Main()
{
    var settings = new JsonSerializerSettings
    {
        PreserveReferencesHandling = PreserveReferencesHandling.None,
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
    };

    var json = "{ \"$ref\": \"THIS IS DATA, NOT A JSON.NET REFERENCE\", \"other\": \"other\" }";
    var deserialized = JsonConvert.DeserializeObject<MyType>(json, settings);

    Console.WriteLine(deserialized.Ref);
}

[JsonObject(IsReference = false)]
public class MyType
{
    [JsonProperty("$ref")]
    public string Ref { get; set; }

    [JsonProperty("other")]
    public string Other { get; set; }
}

Basically, I need to process the "$ref" as a cross-document reference, or a reference to LATER in the current document. For more background, see the Swagger spec for Path Item Object.

Unfortunately, JSON.NET doesn't appear to allow this at all. I've tried a custom IReferenceResolver implementation, but there isn't enough functionality available to resolve the references during deserialization. This is beacuse the references almost always resolve to an item that's later in the document and do not have a $id property.

John Gietzen
  • 48,783
  • 32
  • 145
  • 190
  • use this link to test your string http://jsonlint.com/ and you will immediately see what's wrong also where are your `[` `]` in json..? – MethodMan Sep 11 '15 at 19:22
  • I am trying to get json.net to actually deserialize the $ref reference. This sounds like something a little different than what you are doing, however I wanted to reply to see if you got your document to deserialize $ref's. I am trying to deserialize Swagger as well – Jerrod Horton Feb 18 '16 at 10:23

1 Answers1

1

I think you can get what you want with some pre-processing

var json = "{ \"$ref\": \"THIS IS DATA, NOT A JSON.NET REFERENCE\", \"other\": \"other\" }";

var jObj = JObject.Parse(json);
jObj.Descendants()
    .OfType<JProperty>()
    .Where(p => p.Name == "$ref")
    .ToList()
    .ForEach(p => p.Replace(new JProperty("Ref", p.Value)));

var deserialized =  jObj.ToObject<MyType>();

Console.WriteLine(deserialized.Ref);

BTW: just remove [JsonProperty("...")] attributes...

Eser
  • 12,346
  • 1
  • 22
  • 32