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