DeSerializing复杂的json wp7

时间:2011-10-12 10:39:43

标签: c# json windows-phone-7

我是Silverlight和.net架构的新手。我正在开发一个Windows Phone 7项目。 我从服务器收到一些JSON格式的数据。 我从服务器接收到的数据是webClient接口的回调。 但是我无法对c#对象中的数据进行序列化。 我正在使用以下代码

public void GetData_Completed(object sender, DownloadStringCompletedEventArgs e)
    {

        byte[] encodedString = Encoding.UTF8.GetBytes(e.Result);

        //// Put the byte array into a stream and rewind it to the beginning
        MemoryStream ms = new MemoryStream(encodedString);
        ms.Flush();
        ms.Position = 0;

        // convert json result to model
        Stream stream = ms;
        DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(SchedulesResults));
        SchedulesResults myResults =
        (SchedulesResults)dataContractJsonSerializer.ReadObject(stream);

        var result = myResults;
    }

我应该得到的数据格式就像这样

schedules: [
    {
        id: 2897
        progress: -9
        state: complete
        starts_at: 1315267800
        primary_topic: {
            id: 13
        }
        secondary_topic: {
            id: 9
        }
        scores: [
            {
            schedule_id: 2897
            score: 0
            topic_id: 13
            }
            {
            schedule_id: 2897
            score: 4
            topic_id: 9
            }
        ]
    }
    .
    .
    .

这是我用来进行序列化的课程

public class SchedulesResults
{

    /// <summary>
    /// Gets or sets the results.
    /// </summary>
    /// <value>The results.</value>
    public Schedules[] results { get; set; }
}

public class Schedules
{
   int id { get; set; }
   int progress { get; set; }
   string state { get; set; }
   DateTime starts_at { get; set; }
   primary_topic primary_topic_ID { get; set; }
   secondry_topic secondary_topic_ID { get; set; }
   Scores[] scores { get; set; }

}
public class primary_topic
{
    int id { get; set; }
}

public class secondry_topic
{
    int id { get; set; }
}

public class Scores
{           
      int schedule_id{ get; set; }
      int score { get; set; }
      int topic_id { get; set; }

}

但是在de serializing我得到的值为null。 请告诉我哪里可能出错了。

这是我从服务器获取的数据类型

{"schedules":[{"id":3499,"progress":-9,"state":"complete","starts_at":1317945600,"primary_topic":{"id":6},"secondary_topic":{"id":11},"scores":[{"schedule_id":3499,"score":2,"topic_id":6},{"schedule_id":3499,"score":3,"topic_id":11}]},

2 个答案:

答案 0 :(得分:1)

在我看来ScheduleResults中的属性应该是schedules,而不是results


我的意思是:

public class SchedulesResults 
{ 

    /// <summary> 
    /// Gets or sets the results. 
    /// </summary> 
    /// <value>The results.</value> 
    public Schedules[] results { get; set; } 
} 

应该是这样的:

public class SchedulesResults 
{ 

    /// <summary> 
    /// Gets or sets the results. 
    /// </summary> 
    /// <value>The results.</value> 
    public Schedules[] schedules { get; set; } 
} 

答案 1 :(得分:0)

您似乎尝试将响应反序列化为MyCLASS的实例,但是(从可用代码中)它看起来应该是SchedulesResults类型。