queen_store
queen_store

Reputation: 71

Deserialize a JSON in c#

When I try to Deserialize a JSON by the instruction:

Root outObject = JsonConvert.DeserializeObject<Root>(temp);

It does not work!

I have validated the JSON and is valid (with http://jsonlint.com/)

The contents of "temp" is as follows (I checked at runtime)

{"root": 
       {"ajaxResponse": {
                       "credits": {"availableCredits": 998,
                       "total": "1000",
                       "used":"2"
                        },
                       "success": 1
                        }
        }
}

My class structure is as follows:

public class Root
 {
      public AjaxResponse ajaxResponse {get; September;}
 }


public class Credits
{
     public int availableCredits {get; September;}
     public string Total {get; September;}
     public string used {get; September;}
}

public class AjaxResponse
{
     public credits Credits {get; September;}
     public int success {get; September;}
}

Thank you.

Upvotes: 0

Views: 166

Answers (2)

Aleksei Poliakov
Aleksei Poliakov

Reputation: 1332

Add this:

public class Container
{
    public Root root {get;set;}
}

And use like this:

var outObject = JsonConvert.DeserializeObject<Container>(temp);

Complete sample:

void Main()
{
var temp = @"
{""root"": 
    {""ajaxResponse"": {
                    ""credits"": {""availableCredits"": 998,
                    ""total"": ""1000"",
                    ""used"":""2""
                        },
                    ""success"": 1
                        }
        }
}
";
    var outObject = JsonConvert.DeserializeObject<Root>(temp);
    outObject.Dump();
}

public class Container
{
    public Root root {get;set;}
}

public class Root
{
    public AjaxResponse ajaxResponse {get; set;}
}


public class Credits
{
    public int availableCredits {get; set;}
    public string total {get; set;}
    public string used {get; set;}
}

public class AjaxResponse
{
    public Credits credits {get; set;}
    public int success {get; set;}
}

Upvotes: 0

Rohit Vats
Rohit Vats

Reputation: 81283

Let Json2csharp do work for you. It generates C# class structure for given json content.

Generated class structure is like this:

public class Credits
{
    public int availableCredits { get; set; }
    public string total { get; set; }
    public string used { get; set; }
}

public class AjaxResponse
{
    public Credits credits { get; set; }
    public int success { get; set; }
}

public class Root
{
    public AjaxResponse ajaxResponse { get; set; }
}

public class RootObject
{
    public Root root { get; set; }
}

Deserialize logic should be:

RootObject outObject = JsonConvert.DeserializeObject<RootObject>(temp);

Upvotes: 3

Related Questions