Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why JsonConvert.DeserializeObject not working?

I have a result from web service, the string results is :

{"status":"success","data":{"address":"[email protected]","unconfirmed":[{"tx":"cb2f252078d933f63d9cef52bee8857427d70c1142f41f10567cfad7ef1d2dcb","time_utc":"2015-03-31T19:05:09Z","amount":0.1,"n":0},{"tx":"a34fc5b8b3c29c7046ca8acaedd39280f81597a853f30825856e2f46e498c478","time_utc":"2015-03-31T19:05:01Z","amount":0.1,"n":0}]},"code":200,"message":""}

I'm calling JsonConvert.DeserializeObject:

UTByAddressessResponse data = Serializer.Deserialize(result);

public static T Deserialize<T>(string json)
{
    return JsonConvert.DeserializeObject<T>(json);
}

public class UTByAddressessResponse
{
    public string status { get; set; }
    public UnconfirmedAddressInfo[] data { get; set; }
    public string code { get; set; }
    public string message { get; set; }
}

public class UnconfirmedAddressInfo
{
    public string address { get; set; }
    public List<UT> unconfirmed { get; set; }
}

public class UT
{
    public string tx { get; set; }
    public DateTime time_utc { get; set; }
    public float amount { get; set; }
    public long n { get; set; }
}

But keep getting an error :

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Dice.Common.Objects.UnconfirmedAddressInfo[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

Why ?

like image 624
Haddar Macdasi Avatar asked Dec 05 '22 22:12

Haddar Macdasi


1 Answers

Paste your json to http://json2csharp.com/ It will create the following classes

public class Unconfirmed
{
    public string tx { get; set; }
    public string time_utc { get; set; }
    public double amount { get; set; }
    public int n { get; set; }
}

public class Data
{
    public string address { get; set; }
    public List<Unconfirmed> unconfirmed { get; set; }
}

public class RootObject
{
    public string status { get; set; }
    public Data data { get; set; }
    public int code { get; set; }
    public string message { get; set; }
}

Now you can deserialize as

var obj = JsonConvert.DeserializeObject<RootObject>(json_string);

PS: You can rename your class names, but if you want to rename properties, you should use JsonProperty attribute.

like image 124
EZI Avatar answered Dec 14 '22 18:12

EZI