jaysonragasa
jaysonragasa

Reputation: 1076

Cannot deserialize a JSON object

here's my JSON data

[
    {
        "market_id": "21",
        "coin": "DarkCoin",
        "code": "DRK",
        "exchange": "BTC",
        "last_price": "0.01777975",
        "yesterday_price": "0.01770278",
        "change": "+0.43",
        "24hhigh": "0.01800280",
        "24hlow": "0.01752015",
        "24hvol": "404.202",
        "top_bid": "0.01777975",
        "top_ask": "0.01790000"
    }
]

Here's my class

public class Model_MarketStats
{
    [JsonProperty(PropertyName="market_id")]
    public string market_id { get; set; }
    [JsonProperty(PropertyName = "code")]
    public string code { get; set; }
    [JsonProperty(PropertyName = "exchange")]
    public string exchange { get; set; }
    [JsonProperty(PropertyName = "last_price")]
    public string last_price { get; set; }
    [JsonProperty(PropertyName = "yesterday_price")]
    public string yesterday_price { get; set; }
    [JsonProperty(PropertyName = "change")]
    public string change { get; set; }
    [JsonProperty(PropertyName = "24hhigh")]
    public string highest { get; set; }
    [JsonProperty(PropertyName = "24hlow")]
    public string lowest { get; set; }
    [JsonProperty(PropertyName = "24hvol")]
    public string volume { get; set; }
    [JsonProperty(PropertyName = "top_bid")]
    public string top_bid { get; set; }
    [JsonProperty(PropertyName = "top_ask")]
    public string top_ask { get; set; }
}

The error said

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MintpalAPI.Model_MarketStats_Root' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

This is the way I desialize the JSON

Model_MarketStats = JsonConvert.DeserializeObject<Model_MarketStats>(json);

Upvotes: 0

Views: 3836

Answers (3)

Friyank
Friyank

Reputation: 479

try this , it works and do include this using Newtonsoft.Json; convert json data to string and try this

 Model_MarketStats obj = JsonConvert.DeserializeObject<Model_MarketStats>(jsonstring);

else type cast that json value to list

 Model_MarketStats obj = JsonConvert.DeserializeObject<list<Model_MarketStats>>(jsonstring);

Upvotes: 0

Sean Dong
Sean Dong

Reputation: 615

Your data is an array, therefore, you need to deserialize it as an array/list.

Upvotes: 0

L.B
L.B

Reputation: 116178

You json is an array, use

var stats = JsonConvert.DeserializeObject<List<Model_MarketStats>>(json);

Upvotes: 4

Related Questions