Search code examples
c#jsonlinq

getting Exception Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken when reading json


I have the following JSON:

"printers": {
  "default": "Kyocera ECOSYS M6230cidn KX",
  "userMappings": [
    {
      "user": "050327",
      "printer": "SG Fanelli"
    },
    {
      "user": "050139",
      "printer": "SGPB"
    },
    {
      "user": "050115",
      "printer": "SG Holenstein"
    }
  ]
}

For deserialization I have created the following classes:

public class PrintersDto {
    public string Default { get; set; }
    public IEnumerable<UserPrinterDto> UserMappings { get; set; } = new List<UserPrinterDto>();
}

public class UserPrinterDto {
    public string User { get; set; }
    public string Printer { get; set; }
}

And this is my loading-logic

public PrintersDto GetPrintersConfig() {
    using (var configFileStream = FileIoService.ReadFile(ConfigFilePath)) {
        using (var reader = new StreamReader(configFileStream)) {
            var jsonString = reader.ReadToEnd();
            _configData = (JObject) JsonConvert.DeserializeObject(jsonString);

            var jtoken = _configData.SelectToken("printers");
            return jtoken.Value<PrintersDto>();
        }
    }
}

When I execute this, I get the Exception

Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken

at jtoken.Value<PrintersDto>();

Can someone help me, why this happens and how I can solve this?


Solution

  • using your classes you can get data

    return JObject.Parse(jsonString)["printers"].ToObject<PrintersDto>();