use*_*960 1 c# xml serialization json
// This is my xml data I am trying to map this to my .net classes. By converting XML to json and json back to C# classes.
string xml = @" <ReportTemplate>
<Page Id='1' LayoutId='1'>
<Section Id='1'>
<Body>TEststindfgdfgf</Body>
</Section>`enter code here`
<Section Id='2'>
<Content Id='9834ebcd0e9537c315a42cf0d8ed32745f89827c' Type='News'></Content>
<Content Id='9834ebcd0e9537c315a42cf0d8ed32745f89827c' Type='News' ></Content>
</Section>
<Section Id='3'>
<Content Id='9834ebcd0e9537c315a42cf0d8ed32745f89827c' Type='News'></Content>
</Section>
</Page>
<Page Id='2' LayoutId='1'>
<Section Id='1'>
<Content Id='9834ebcd0e9537c315a42cf0d8ed32745f89827c' Type='News'></Content>
<Content Id='9834ebcd0e9537c315a42cf0d8ed32745f89827c' Type='News'></Content>
</Section>
<Section Id='2'>
<Content Id='9834ebcd0e9537c315a42cf0d8ed32745f89827c' Type='News'></Content>
</Section>
<Section Id='3'>
<Body>dfgdgggf;</Body>
</Section>
</Page>
</ReportTemplate>";
public class ReportTemplate
{
public List<Page> Page { get; set; }
}
public class Page
{
public string Id { get; set; }
public string LayoutId { get; set; }
public List<Section> Section { get; set; }
}
public class Section
{
public string Id { get; set; }
public string Body { get; set; }
public List<Content> Content { get; set; }
}
public class Content
{
public string Id { get; set; }
public string Type { get; set; }
}
var xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
var json = JsonConvert.SerializeXmlNode(xmldoc,Newtonsoft.Json.Formatting.Indented, true);
var obj = JsonConvert.DeserializeObject<ReportTemplate>(Regex.Replace(json, "(?<=\")(@)(?!.*\":\\s )", string.Empty, RegexOptions.IgnoreCase));
Run Code Online (Sandbox Code Playgroud)
//这是我得到的错误
Newtonsoft.Json.JsonSerializationException:'无法将当前JSON对象(例如{"name":"value"})反序列化为类型'System.Collections.Generic.List`1 [LintoXML.Program + Content]',因为类型需要JSON数组(例如[1,2,3])正确反序列化.要修复此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型,使其成为普通的.NET类型(例如,不是像整数这样的基本类型,而不是类似的集合类型可以从JSON对象反序列化的数组或List.JsonObjectAttribute也可以添加到类型中以强制它从JSON对象反序列化.路径'Page [0] .Section [2] .Content.Id',第27行,第17位.'
将XML序列化为JSON后,复制JSON并通过引用此答案为其生成类.以下是课程:
public class Rootobject
{
public Reporttemplate ReportTemplate { get; set; }
}
public class Reporttemplate
{
public Page[] Page { get; set; }
}
public class Page
{
public string Id { get; set; }
public string LayoutId { get; set; }
public Section[] Section { get; set; }
public string text { get; set; }
}
public class Section
{
public string Id { get; set; }
public string Body { get; set; }
public object Content { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后将JSON反序列化为这些类:
var xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
var fromXml = JsonConvert.SerializeXmlNode(xmldoc);
var fromJson = JsonConvert.DeserializeObject<Rootobject>(fromXml);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4550 次 |
| 最近记录: |