为什么JsonConvert.DeserializeObject不起作用?

时间:2015-03-31 19:33:28

标签: c# json serialization

我有来自Web服务的结果,字符串结果是:

{"status":"success","data":{"address":"aa@aa.aa","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":""}

我正在调用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; }
    }

但不断收到错误:

  

无法反序列化当前的JSON对象(例如{&#34; name&#34;:&#34; value&#34;})   进入类型&#39; Dice.Common.Objects.UnconfirmedAddressInfo []&#39;因为   type需要一个JSON数组(例如[1,2,3])才能正确反序列化。

为什么?

2 个答案:

答案 0 :(得分:2)

将你的json粘贴到http://json2csharp.com/它将创建以下类

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

现在您可以反序列化为

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

PS:您可以重命名您的类名,但如果您想重命名属性,则应使用JsonProperty属性。

答案 1 :(得分:1)

问题在于

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 UTByAddressessResponse
    {
        public string status { get; set; }
        public UnconfirmedAddressInfo data { get; set; } // not array

        public string code { get; set; }
        public string message { get; set; }
    }