反序列化JSON来字典,DataContractJsonSerializer字典、序列化、JSON、DataContractJsonSerializer

2023-09-03 00:29:58 作者:我本無心為何有愛!

我收到以下JSON结果INT响应:

I receive the following JSON result int the response:

{"result": { "":-41.41, "ABC":0.07, "XYZ":0.00, "Test":0.00 }}

我有prepared以下类deserializating:

I've prepared the following class for deserializating:

[DataContract]
public sealed class RpcResponse
{
    [DataMember(Name = "result")]
    public List<KeyValuePair<string, decimal>> Result { get; set; }
}

然而,当我特林与 DataContractJsonSerializer 结果属性最终与具有零项反序列化。 (也没有宣布何时上班结果词典&LT;字符串,小数&GT;

However when I'm tring to deserialize it with DataContractJsonSerializer the Result property ends up with having zero entries. (Also doesn't work when declaring Result as Dictionary<string, decimal>)

有没有办法与 DataContractJsonSerializer

推荐答案

请参阅此 SO回答

根据您的JSON定义DataContract。

Define the DataContract according to your JSON.

[DataContract]
public class CustomObject
{
    [DataMember(Name = "Name")]
    public string Name { get; set; }

    [DataMember(Name = "Age")]
    public string Age { get; set; }

    [DataMember(Name = "Parent")]
    public Dictionary<string, object> Parent { get; set; }
}

使用的DataContract类,而反序列化。

Use the DataContract class while deserialization.

using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
    DataContractJsonSerializerSettings settings = 
            new DataContractJsonSerializerSettings();
    settings.UseSimpleDictionaryFormat = true;

    DataContractJsonSerializer serializer = 
            new DataContractJsonSerializer(typeof(CustomObject), settings);

    CustomObject results = (CustomObject)serializer.ReadObject(ms);
    Dictionary<string, object> parent = results.Parent;
}