Home > OS >  getting Exception Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken when readi
getting Exception Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken when readi

Time:09-17

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?

CodePudding user response:

using your classes you can get data

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

CodePudding user response:

Replace

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

with

return _configData.SelectToken("printers").ToObject<PrintersDto>();
  • Related