user1789782
user1789782

Reputation: 197

Newtonsoft.Json Custom Root Name for Deserialization

I have this class that defines the json format:

public class ResultType
{
    public bool status { get; set; }
    public string message { get; set; }
}

The actual json looks like this:

{"result":{"status":true,"message":"Success"}}

How can I override the root attribute when de-serializing the json to "result"

Upvotes: 2

Views: 2351

Answers (2)

user1789782
user1789782

Reputation: 197

I have a central deserialization method, so I'm trying to avoid type specific code as much as possible.

I used the following to resolve the problem, maybe not as sexy as I was hoping for but it works.

public class ResultType
{
    public ResultDetailType result { get; set; }
}
public class ResultDetailType
{ 
    public bool status { get; set; }
    public string message { get; set; }
}

Upvotes: 0

Krunal Mevada
Krunal Mevada

Reputation: 1655

JObject jsonResponse = JObject.Parse(jsonString);
ResultType _Data = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultType>(jsonResponse["result"].ToString());

Console.WriteLine(_Data.status);

Fiddle: https://dotnetfiddle.net/gjYS2p

Upvotes: 2

Related Questions