3

I'm calling a REST service using Refit and it is deserializing the JSON that is returned using a class definition I provide. One property of the object returned is JSON so I effectively have nested JSON.

I want to deserialize the nested property as a string as I don't know ahead of time what type it is.

Here is the JSON

{
    "Id": "f90b443d-300c-4e6d-a488-eb4bbf62889e",
    "Type": "e9ccd222-c252-4846-bf16-5936820a3177",
    "SharedName": null,
    "Cache": 1,
    "Data": {
        "Description": "Central Coast"
    }
},
{
    "Id": "f863581b-67e2-49e0-83c9-ab5820715f4f",
    "Type": "7d1c81bd-0b94-4b88-998b-14a8fb9dbbfd",
    "SharedName": null,
    "Cache": 1,
    "Data": {
        "Name": "Emergency Department (ED) Report"
    }
}

Here is my class definition

public class EntityDetails
{
    public string Id { get; set; }
    public string Type { get; set; }
    public string SharedName { get; set; }
    public int Cache { get; set; }
    public string Data { get; set; }
}

But I get this error:

"Error reading string. Unexpected token: StartObject. Path '[0].Data', line 7, position 14."

Is there a JSON attribute that will tell the deserializer what to do?

Steve Chadbourne
  • 6,873
  • 3
  • 54
  • 82
  • *I want to deserialize the nested property as a string* -- exactly **how** do you want to deserialize it? Is it always an object with a single `"Name"` property, or could it be anything? – dbc Sep 07 '17 at 23:26
  • It could be anything or could be null. You can see above that the first item has a property of Description and the second a property of Name. – Steve Chadbourne Sep 07 '17 at 23:30
  • OK, then what do you want in the string? The raw JSON? In that case, you could consider using `RawConverter` from [How can I serialize and deserialize a type with a string member that contains “raw” JSON, without escaping the JSON in the process](https://stackoverflow.com/a/40539360/3744182). (From the error message, it seems that you are using Json.NET to deserialize your JSON, which is why I linked to that answer.) – dbc Sep 07 '17 at 23:32
  • 1
    I'm using Newtonsoft.Json but the raw converter worked thanks. Please write it as an answer and I'll mark it as correct, – Steve Chadbourne Sep 07 '17 at 23:40
  • Cool will do. Thanks for the timely help. – Steve Chadbourne Sep 07 '17 at 23:50

1 Answers1

0

You could change Data to object or Newtonsoft.Json.Linq.JObject. and then ToString it.

public class EntityDetails
{
    (...)
    public Newtonsoft.Json.Linq.JObject Data { get; set; }
}

(...)
var x = JsonConvert.DeserializeObject<EntityDetails>(jsonString);
var dataAsString = x?.Data?.ToString();
tymtam
  • 31,798
  • 8
  • 86
  • 126