1

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?

2 Answers 2

4

using your classes you can get data

return JObject.Parse(jsonString)["printers"].ToObject<PrintersDto>();
Sign up to request clarification or add additional context in comments.

Comments

0

Replace

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

with

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.