0

我使用以下类创建 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 放入普通字符串?

4

1 回答 1

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"]);
}
于 2013-06-25T12:52:50.873 回答