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

本文关键字:反序列化 对象 字符串 JSON NET | 更新日期: 2023-09-27 17:49:15

我试图将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;
}
希望有人能解决这个问题!我一整天都在努力……

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

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

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