tttt
tttt

Reputation: 133

C# serialize json to class

This is my json :

"{\"sctoken\":\"a50395d5-571983f3-b394-4c6f-a26a-f95ae125fad6\",\"tms\":[{\"name\":\"yyy\",\"url\":\"zz\"},{\"name\":\"xxx\",\"url\":\"http\"},{\"name\":\"xxx\",\"url\":\"xx\"}],\"user_descr\":\"cx\"}"

this how I convert json to class :

LoginResult loginResult = JsonConvert.DeserializeObject<LoginResult>(result.ToString());


class LoginResult
{
    string sctoken { set; get; }
    List<Maps> tms { set; get; }
}

class Maps
{
    public string name { get; set; }
    public string url { get; set; }
}

and my object LoginResult is empty

Upvotes: 1

Views: 194

Answers (3)

Shahrukh Ahmad
Shahrukh Ahmad

Reputation: 153

You are missing Public in your LoginResult class , just put Public access modifier and it would start working (like this):

  class LoginResult
    {
        public string sctoken { set; get; }
        public List<Maps> tms { set; get; }
    }

Upvotes: 0

Peter B
Peter B

Reputation: 24136

It should work if you make the properties and the classes all public, so the deserializer can find & access them:

public class LoginResult
{
    public string sctoken { set; get; }
    public List<Maps> tms { set; get; }
}

public class Maps
{
    public string name { get; set; }
    public string url { get; set; }
}

You are also missing the element user_descr but that is not essential (you can still add it, or omit it if you don't need it).

Upvotes: 1

Jay
Jay

Reputation: 723

Try This

LoginResult loginResult = JsonConvert.DeserializeObject<RootObject>(result.ToString());
    public class Tm
    {
        public string name { get; set; }
        public string url { get; set; }
    }

    public class RootObject
    {
        public string sctoken { get; set; }
        public List<Tm> tms { get; set; }
        public string user_descr { get; set; }
    }

Upvotes: 2

Related Questions