在c#中反序列化JSON



当我尝试通过以下指令对JSON进行反序列化时:

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

它不起作用!

我已经验证了JSON并且是有效的(http://jsonlint.com/)

"temp"的内容如下(我在运行时检查过)

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

我的班级结构如下:

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

谢谢。

让Json2csharp为您工作。它为给定的json内容生成C#类结构。

生成的类结构如下:

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

反序列化逻辑应为:

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

添加此项:

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

像这样使用:

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

完整样品:

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

相关内容

  • 没有找到相关文章

最新更新