1

I have the following problem:

(UserAttribues)Newtonsoft.Json.JsonConvert.DeserializeObject("{\"username\":\"Someone\"}");

throws an Error:

"Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'UserAttribues'."

The class is simple as:

 [Serializable]
 public class UserAttribues
 {
    public string username;
 }

Any help appreciated. (I also tried "{\"username\":\"\"Someone\"\"}")

4
  • 1
    Did you try the generic version? JsonConvert.DeserializeObject<UserAttributes>(... Commented Mar 4, 2016 at 12:34
  • oh that actually worked... Can you explain why? (if you post as an answer ill accept it) Commented Mar 4, 2016 at 12:45
  • 1
    I don't want to steal the answer from @StarterPack, but it is because you are specifically telling it the type you want and it will do its best to map the fields. With a cast you rely on type compatibility. C# doesn't just know how to map type members between any two types. Commented Mar 4, 2016 at 12:56
  • All right, thanks a lot for help and explanation, makes sense. Commented Mar 4, 2016 at 13:00

2 Answers 2

7

You can use JsonConvert.Deserialize for this. Use it like this:

 var attr = JsonConvert.DeserializeObject<UserAttribues>("{\"username\":\"Someone\"}");
Sign up to request clarification or add additional context in comments.

Comments

2

When you use the non-generic version of the DeserializeObject() method you get a JObject. As the error shows, you cannot cast this JObject to a UserAttributes object. The reason is that type casting is allowed in specific cases, like casting between compatible primitive types (e.g. between int and double) or between classes which are related.

For example, if we have a base class and a derived class, class Animal and class Reptile : Animal, you can safely cast an object of type Reptile to Animal, or the other way around (if your object is indeed a Reptile, otherwise you'll get an error).

Therefore, the reason your sample code doesn't work is because the JObject you have and the UserAttributes you want to get aren't related in any way. The solution, as already pointed out by @StarterPack, is to use the generic version DeserializeObject<some_type>().

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.