2

If the class consists of simple JSON-compatible types, MyClass obj = JsonConvert.DeserializeObject<MyClass>(JSONtext); does the job quite nicely. If MyClass contains enum or struct properties, the DeserializeObject<> method returns null. I'm currently iterating through the JSON response deserialized into a JObject, assigning values to the inner class created, and returning it. Is there a better way to deserialize the JSON string into an heterogeneous class object?

class MyClass
{
    public Int32 wishlistID;
    public Basket currentBasket; //struct
    public List<Int32> items;
    public dStatus _dStatus; //enum
}

Edit: turns out that, for some reason, all Basket's properties had the private modifier; of course they couldn't be accessed and result to be therefore null. Switching it to public did the trick.

1 Answer 1

6

Your members have to be public in order for this to work.

This doesn't work:

public class MyClass
{
    Int32 a;
    string b; //struct
}

string json = "{ a: 7, b:'abc' }";
MyClass cc = JsonConvert.DeserializeObject<MyClass>(json);

This does work:

public class MyClass
{
    public Int32 a;
    public string b; //struct
}

string json = "{ a: 7, b:'abc' }";
MyClass cc = JsonConvert.DeserializeObject<MyClass>(json);

Edit:

So after we got through that public stuff you claim that structs\enums don't pass.
Here's and example that they do:

public class MyClass
{
    public Int32 a;
    public test b;
    public eMyEnum c;
}

public struct test
{
    public string str;
}

public enum eMyEnum
{
    A = 0,
    B
}

string json = "{ a: 7, b: {str:'str'}, c: 'B' }";
MyClass cc = JsonConvert.DeserializeObject<MyClass>(json);
Sign up to request clarification or add additional context in comments.

4 Comments

Edited, forgot to put the public modifiers, thanks!
As for the b property though, if it was to be a Basket struct, the method would still return null.
@ShinyPhoenix - I've edited and added an example that structs\enums work. Please provide some more info so we can spot your bug.
Argh, they do indeed! For some reason - can't realize what I was thinking at the time I wrote the code - all the struct's properties were private! Switching them to public did the trick. Thank you!

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.