15

我正在尝试使用 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"];

输出 JSON

"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 中删除根

4

2 回答 2

26

JSON.Net 有一种SerializeXmlNode()方法可以完全满足您的需求。只需传递trueomitRootObject参数。观察:

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"}]}
于 2013-10-11T14:23:34.610 回答
0
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());
}

使用某种变体。

于 2013-10-11T06:49:39.303 回答