0

我使用DataContractJsonSerializer將JSON字符串轉換爲類,但始終返回一個空對象。 我在記事本中用'JSON查看器'擴展名測試了字符串,是有效的。搜索長時間的錯誤並比較其他示例。DataContractJsonSerializer不工作

這是縮寫形式我的JSON字符串:

{ 
"error":[], 
"result": { 
     "BCH": {"aclass":"currency","altname":"BCH","decimals":10,"display_decimals":5}, 
     "DASH": {"aclass":"currency","altname":"test"} 
    } 
} 

的類GetAssetInfoResponseassetinfo的包含屬性與數據成員屬性,但屬性結果(後反序列化)不包含任何物體。

[DataContract] 
[KnownType(typeof(AssetInfo))] 
public class GetAssetInfoResponse 
{ 
    [DataMember(Name = "error")] 
    public List<string> Error { get; set; } 

    [DataMember(Name = "result")] 
    public List<Dictionary<string, AssetInfo>> Result { get; set; } 
} 

[DataContract] 
public class AssetInfo 
{ 
    /// <summary> 
    /// Alternate name. 
    /// </summary> 
    [DataMember(Name = "altname")] 
    public string Altname { get; set; } 

    /// <summary> 
    /// Asset class. 
    /// </summary> 
    [DataMember(Name = "aclass")] 
    public string Aclass { get; set; } 

    /// <summary> 
    /// Scaling decimal places for record keeping. 
    /// </summary> 
    [DataMember(Name = "decimals")] 
    public int Decimals { get; set; } 

    /// <summary> 
    /// Scaling decimal places for output display. 
    /// </summary> 
    [DataMember(Name = "display_decimals")] 
    public int DisplayDecimals { get; set; } 
} 

這是我的測試代碼:

 var stream = new MemoryStream(Encoding.Unicode.GetBytes(strName)) 
     { 
      Position = 0 
     }; 
     var serializer = new DataContractJsonSerializer(typeof(GetAssetInfoResponse)); 
     GetAssetInfoResponse test = (GetAssetInfoResponse)serializer.ReadObject(stream); 

     Console.ReadLine(); 

我不能使用Newtonsoft.Json擴展,因爲項目不應包含任何外部的依賴。 有沒有另一種方法將JSON字符串轉換爲類?

謝謝您的時間

回答

1

您聲明Result作爲List<Dictionary<string, AssetInfo>>但是從格式,它看起來像一本字典,而不是一個字典列表(因爲它與{開始,這是用於對象或字典,而不是用於數組/列表的[)。要使用此格式的詞典,你需要配置UseSimpleDictionaryFormat財產

var serializer = new DataContractJsonSerializer(typeof(GetAssetInfoResponse), new DataContractJsonSerializerSettings 
{ 
    UseSimpleDictionaryFormat = true 
}); 

使用此設置這種變化,它的工作:

public Dictionary<string, AssetInfo> Result { get; set; } 
+0

謝謝!現在它可以工作。 – patbec

相關問題