目录
我正在尝试使用 JSON.NET 从xml创建JSON
XmlDocument docPerson = new XmlDocument();
docPerson.LoadXml(xmlPerson); //xmlPerson is the xml from above
JObject personDefinition = JObject.Parse(JsonConvert.SerializeObject(docPerson));
Tasks.personDefinition = personDefinition["personDefinition"];
输出数据兼容
"person":{"person":[{"personId":"1","firstName":"Name1","lastName":"lastName1"}, {"personId":"3","firstName":"Name2","lastName":"lastName2"}]}
我不需要外部人员,只需要以下json
必需的 JSON
"person":[{"personId":"1","firstName":"1","lastName":"Weight"},{"personId":"3","firstName":"4","lastName":"Pulse Ox"}]}
我尝试使用 .first 方法,但它抛出了一个错误。任何人都可以建议如何从输出 json 中删除根
JSON.Net 有一个SerializeXmlNode()
方法,可以完全按照你想要的方式做。 只需将true
传递给omitRootObject
参数即可。观察:
string xmlPerson = @"<PersonDefinition><Person><name>Nicolas</name><age>22</age></Person><Person><name>Pankaj</name><age>25</age></Person></PersonDefinition>";
XmlDocument docPerson = new XmlDocument();
docPerson.LoadXml(xmlPerson);
string json = JsonConvert.SerializeXmlNode(docPerson, Formatting.None, true);
Console.WriteLine(json);
输出:
{"Person":[{"name":"Nicolas","age":"22"},{"name":"Pankaj","age":"25"}]}
string xml = "<PersonDefinition><Person><name>Nicolas</name><age>22</age></Person><Person><name>Pankaj</name><age>25</age></Person></PersonDefinition>";
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person[]), new XmlRootAttribute("PersonDefinition"));
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
using (TextReader reader = new StringReader(xml))
{
Person[] people = xmlSerializer.Deserialize(reader) as Person[];
string json = jsonSerializer.Serialize(new Person());
}
使用这种变体。