开发者

How do I parse this json-response?

The response is structured like this, this is an extract, might be missing a curly brace:

{"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"}

And I get cast exceptions when parsing the response string even though all the datamembers in the object are strings.

I'm using System.Runtime.Serialization.Json to deserialize the objects.

Right now I'm doing it like this:

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


As mentioned already, you're missing a trailing } from the JSON. Assuming that what you receive is properly formatted and consistent JSON, then your Currency class should look something like this:

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

Your deserialization code looks fine, though you could consider using JSON.NET if you're still having problems, as described here: Deserializing variable Type JSON array using DataContractJsonSerializer

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜