如何将JSON字符串反序列化为具有不同类型变量的类
本文关键字:类型变量 JSON 字符串 反序列化 | 更新日期: 2023-09-27 18:19:45
我使用以下类创建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放入一个正常的字符串中?
一个简单的调整是使用这样的字典:
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"]);
}