C#.NET将JSON字符串反序列化为对象

时间:2016-06-26 07:24:45

标签: c# json json.net json-deserialization

我正在尝试将JSON反序列化为对象“MarginBalance”。当我尝试反序列化这个JSON:

{"totalValue":"0.00091979","pl":"0.00000000","lendingFees":"0.00000000","netValue":"0.00091979","totalBorrowedValue":"0.00000000","currentMargin":"1.00000000"}

到这个对象:

public class MarginBalance : IMarginBalance
{ 
    [JsonProperty("totalValue")]
    public double TotalValue { get; set; }

    [JsonProperty("pl")]
    public double PL { get; set; }

    [JsonProperty("lendingFees")]
    public double LendingFees { get; set; }

    [JsonProperty("netValue")]
    public double NetValue { get; set; }

    [JsonProperty("totalBorrowedValue")]
    public double TotalBorrowedValue { get; set; }

    [JsonProperty("currentMargin")]
    public double CurrentMargin { get; set; }
}

实现此接口:

public interface IMarginBalance
{
    double TotalValue { get; } 
    double PL { get; } 
    double LendingFees { get; } 
    double NetValue { get; } 
    double TotalBorrowedValue { get; } 
    double CurrentMargin { get; }
}

它返回null。这是我的反序列化代码:

var postData = new Dictionary<string, object>();
var data = PostData<IDictionary<string, MarginBalance>>("returnMarginAccountSummary", postData);
if (data != null)
{
    // never reaches here 
    var returnData = new Dictionary<string, IMarginBalance>();
    foreach (string key in data.Keys)
    {
        returnData.Add(key, data[key]);
    }
    return returnData;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private T PostData<T>(string command, Dictionary<string, object> postData)
{
    return ApiWebClient.PostData<T>(command, postData);
} 

public T PostData<T>(string command, Dictionary<string, object> postData)
{
    postData.Add("command", command);
    postData.Add("nonce", Helper.GetCurrentHttpPostNonce());

    var jsonString = PostString(Helper.ApiUrlHttpsRelativeTrading, postData.ToHttpPostString());
    var output = JsonSerializer.DeserializeObject<T>(jsonString);

    return output;
}

希望有人可以解决这个问题!我一整天都在努力......提前谢谢。

1 个答案:

答案 0 :(得分:1)

Json中的数字被撇号包围,这意味着它们是字符串,而不是数字。您可以尝试从Json字符串中的数字中删除撇号,或者在对象中将字段类型从double更改为字符串。

JsonProperty中使用的MarginBalance属性属于Newtonsoft.Json.Serialization命名空间。要反序列化对象,您应该使用JsonConvert.DeserializeObject<MarginBalance>(jsonString)