2013-06-25 22 views
0

我用下面的类来创建JSON:我如何反序列化JSON字符串与具有不同类型的变量一类?

public class Detail 
{ 
    public bool Correct { get; set; } 
    public bool Response { get; set; } 
    public HtmlText Text { get; set; } 
    public string ImageFile { get; set; } 
    public HtmlText Explanation { get; set; } 
} 

我想反序列化到这一点:

public class Answer 
{ 
    public bool Correct { get; set; } 
    public bool Response { get; set; } 
    public string Text { get; set; } 
    public string ImageFile { get; set; } 
    public string Explanation { get; set; } 
} 

要做到这一点,我有以下几点:

public static string ToJSONString(this object obj) 
{ 
    using (var stream = new MemoryStream()) 
    { 
     var ser = new DataContractJsonSerializer(obj.GetType()); 
     ser.WriteObject(stream, obj); 
     return Encoding.UTF8.GetString(stream.ToArray()); 
    } 
} 

这里有一个我的数据样本:

[ 
    {"Correct":false, 
    "Explanation":{"TextWithHtml":null}, 
    "ImageFile":null, 
    "Response":false, 
    "Text":{"TextWithHtml":"-1 1 -16 4"} 
    }, 
    {"Correct":false, 
    "Explanation":{"TextWithHtml":null}, 
    "ImageFile":null, 
    "Response":false, 
    "Text":{"TextWithHtml":"1 -1 -4 16"} 
    }, 
    {"Correct":false, 
    "Explanation":{"TextWithHtml":null}, 
    "ImageFile":null, 
    "Response":false, 
    "Text":{"TextWithHtml":"1 -1 4 2147483644"} 
    }] 

和我的代码:

IList<Answer> answers = JSON.FromJSONString<List<Answer>>(detailsJSON) 

它给我一个错误消息说:

{"There was an error deserializing the object of type 
System.Collections.Generic.List`1[[Answer, Models, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]. 
End element 'Explanation' from namespace '' expected. Found element 'TextWithHtml' from namespace ''."} 
System.Exception {System.Runtime.Serialization.SerializationException} 

有没有办法,我可以改变这种做法,它会将htmlText放入一个普通的字符串一个简单的方法?

+1

我觉得没有直接的方法。您可以注册自定义转换器要做到这一点,你可以找到的解释你所需要的: http://james.newtonking.com/projects/json/help/?topic=html/T_Newtonsoft_Json_Converters_CustomCreationConverter_1.htm和这里的代码示例:http://james.newtonking.com/projects/json/help/?topic=html/DeserializeCustomCreationConverter.htm – C4stor

+0

你有没有得到一个机会去尝试我的建议? –

回答

0

一个简单的调整是使用词典这样的:

public class Answer 
{ 
    public bool Correct { get; set; } 
    public bool Response { get; set; } 
    public Dictionary<string, string> Text { get; set; } 
    public string ImageFile { get; set; } 
    public Dictionary<string, string> Explanation { get; set; } 
} 

反序列化和访问这样的值;

var answers = JsonConvert.DeserializeObject<List<Answer>>(detailsJSON); 

foreach (var answer in answers) 
{ 
    Console.WriteLine(answer.Text["TextWithHtml"]); 
    Console.WriteLine(answer.Explanation["TextWithHtml"]); 
} 
相关问题