Johnny Bueti
Johnny Bueti

Reputation: 658

Deserialize JSON string into a C# complex class object

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.

Upvotes: 2

Views: 9693

Answers (1)

Amir Popovich
Amir Popovich

Reputation: 29846

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);

Upvotes: 6

Related Questions