我如何解析这个json响应?

时间:2011-06-02 12:24:54

标签: c# json parsing windows-phone-7

响应的结构如下,这是一个摘录,可能缺少大括号:

{"2":{"date":1306411951,"price":4.8003,"low":"4.80000000","high":"4.80060000","nicedate":"15:12"},"6":{"date":1306418941,"price":4.654175,"low":"4.40000000","high":"4.80000000","nicedate":"17:02"}

在解析响应字符串时,我得到强制转换异常,即使对象中的所有数据成员都是字符串。

我正在使用System.Runtime.Serialization.Json来反序列化对象。

现在我这样做:

        Currency[] MapJSONToObjects(string jsonString)
    {
        using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
        {
            //Parse
            var ser = new DataContractJsonSerializer(typeof(Currency[]));
            Currency[] currencies = (Currency[])ser.ReadObject(ms);
            return currencies;
        }
    }

1 个答案:

答案 0 :(得分:2)

如上所述,您错过了JSON中的尾随}。假设您收到的内容格式正确且JSON一致,那么您的Currency类应如下所示:

[DataContract]
public class Currency
{
    [DataMember(Name = "date")]
    public int Date { get; set; }
    [DataMember(Name = "price")]
    public double Price { get; set; }
    [DataMember(Name = "low")]
    public string Low { get; set; }
    [DataMember(Name = "high")]
    public string High { get; set; }
    [DataMember(Name = "nicedate")]
    public string NiceDate { get; set; }
}

您的反序列化代码看起来很好,但如果您仍然遇到问题,可以考虑使用JSON.NET,如下所述:Deserializing variable Type JSON array using DataContractJsonSerializer