【问题标题】:Parsing Json C#解析 Json C#
【发布时间】:2015-01-23 11:18:15
【问题描述】:

我在 Windows Phone 8 应用程序中解析 C# 中的 JSON 时遇到很大问题。

当我尝试执行这部分代码时,应用程序关闭。当 C# 代码反序列化 json 时会出现问题。

见下方代码:C#(反序列化+类形式)和JSON结果。

感谢您的回答。

public partial class MyGrades : PhoneApplicationPage
{
    string token = string.Empty;
    string mail = string.Empty;


    public class MyGradesJson
    {
        [JsonProperty("periods")]
        public Periods periods { get; set; }
    }

    public class Periods
    {
        [JsonProperty("period")]
        public List<Perioddata> perioddata { get; set; }
    }

    public class Perioddata
    {
        [JsonProperty("period")]
        public Period period { get; set; }
    // [JsonProperty("name")]
    // public List disciplines { get; set; }
    }

    public class Period
    {
        [JsonProperty("id")]
        public int id { get; set; }
        [JsonProperty("name")]
        public string name { get; set; }
        [JsonProperty("start_date")]
        public string start_date { get; set; }
        [JsonProperty("end_date")]
        public string end_date { get; set; }
    }

    HttpResponseMessage response = await httpClient.SendAsync(requestMessage);
    string responseAsString = await response.Content.ReadAsStringAsync();
    var resJson = JsonConvert.DeserializeObject<Periods>(responseAsString);
}

这是 Json 答案:

{
"periods":[
{
"period":{
"id":1,
"name":"Year 1",
"start_date":"2000-01-01",
"end_date":"2001-06-30"
},
"disciplines":[
{
"discipline":{
"id":6,
"name":"Potions"
},
"grades":[
{
"id":11,
"note":2,
"coefficient":2,
"assessment":"yolo",
"teacher":{
"id":2,
"user_id":4,
"login":"snape_se",
"name":"Snape, Severus"
}
},
{
"id":15,
"note":10,
"coefficient":1,
"assessment":"test",
"teacher":{
"id":2,
"user_id":4,
"login":"snape_se",
"name":"Snape, Severus"
         }
     }
  ]
     }
     ]
     }
   ]
}

【问题讨论】:

  • "应用程序关闭":您的全局异常处理程序显示什么? (我你还没有设置一个然后先这样做。)否则可以使用调试器获取未处理的异常。除非您有异常的详细信息,否则您就是在浪费时间。
  • 我尝试了很多次以显示调试器控制台但无法达到我的目标。
  • VS 有多种选择。 1. 检查输出窗口是否有异常,然后使用 Debug |抛出异常时会中断。 2. 查看stackoverflow.com/q/793100/67392 设置全局处理程序。 3. 在线程池中用 try/catch 块包围你的代码(Debugger.Break() 是一个有用的方法)。
  • “我尝试了很多次来显示调试器控制台,但无法达到我的目标”那么你的问题应该是关于这个问题的。你需要解决这个问题才能继续前进。
  • 您介意帮我显示调试控制台吗?因为我在互联网上找到的所有信息对我没有多大帮助。谢谢!

标签: c# json parsing deserialization


【解决方案1】:

我认为您的应用程序已损坏,因为您的resJson 中有null。 您提供的 JSON 不会反序列化为 Perods 对象实例。 尝试从 JSON 生成 C# 类。如果您的 VS 版本中没有此功能,请尝试使用在线工具。例如http://json2csharp.com/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多