1

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;
        }
    }
2
  • 1
    Are you missing a trailing } ? Or maybe my eyes deceive me. Commented Jun 2, 2011 at 12:26
  • This is not valid JSON. There's at least a curly brace missing at the end. Commented Jun 2, 2011 at 12:26

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

The response is fine, I checked with a json-validator. My class looks exactly like your suggestion (no, really, exactly like that) but I think the problem lies in the index. It doesn't cast correctly since there's no property for the index and the index isn't named either. I don't know how to handle that specific scenario...
Checking JSON.NET now, seems sweet.
Although this didn't solve my problem, it is indeed the best way in most cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.