使用JSON.Net将XML转换为JSON字符串时未获得所需的结果

时间:2015-09-24 07:32:45

标签: c# json xml json.net

以下是我们尝试将其转换为JSON字符串的XML字符串。

  <?xml version="1.0" encoding="utf-16" ?> 
  <MyClass>
  <Id>1</Id> 
  <Names>
  <string>Surya</string> 
  <string>Kiran</string> 
  </Names>
  <ClassTypes>
  <Types>
  <TypeId>1</TypeId> 
  <TypeName>First Name</TypeName> 
  </Types>
  <Types>
  <TypeId>2</TypeId> 
  <TypeName>Last Name</TypeName> 
  </Types>
  </ClassTypes>
  <Status>1</Status> 
  </MyClass>

使用以下代码,我得到如下结果

xmlString = "<?xml version=\"1.0\" encoding=\"utf-16\"?><MyClass><Id>1</Id><Names><string>Surya</string><string>Kiran</string></Names><ClassTypes><Types><TypeId>1</TypeId><TypeName>First Name</TypeName></Types><Types><TypeId>2</TypeId><TypeName>Last Name</TypeName></Types></ClassTypes><Status>1</Status></MyClass>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
doc.ChildNodes.OfType<XmlNode>().Where(x => x.NodeType == XmlNodeType.XmlDeclaration).ToList().ForEach(x => doc.RemoveChild(x));
jsonString = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.None, true);

实际结果

  

{&#34;标识&#34;:&#34; 1&#34;&#34;名称&#34; {&#34;串&#34;:[&#34;苏里亚&#34; &#34;基兰&#34;]}&#34;类类别&#34; {&#34;类型&#34;:[{&#34; TYPEID&#34;:&#34; 1&#34; &#34;类型名&#34;:&#34;第一   姓名&#34;},{&#34; TypeId&#34;:&#34; 2&#34;,&#34; TypeName&#34;:&#34;姓氏&#34;}]},&#34 ;状态&#34;:&#34; 1&#34;}

预期结果

  

{&#34;标识&#34;:1,&#34;名称&#34;:[&#34;苏里亚&#34;&#34;基兰&#34],&#34;类类别&# 34;:[{&#34; TYPEID&#34;:1,&#34;类型名&#34;:&#34;第一   姓名&#34;},{&#34; TypeId&#34;:2,&#34; TypeName&#34;:&#34;姓氏&#34;}],&#34;状态&#34;:0}

我们需要将此结果反序列化到下面的类

public class MyClass
{
    public int Id { get; set; }
    public IList<string> Names { get; protected set; }
    public IList<Types> ClassTypes { get; protected set; }
    public StatusType Status { get; set; }

    public MyClass()
    {
        Names = new List<string>();
        ClassTypes = new List<Types>();
        Status = StatusType.Active;
    }
}
public class Types
{
    public int TypeId { get; set; }
    public string TypeName { get; set; }
}

public enum StatusType
{
    Active = 0,
    InActive = 1
}

1 个答案:

答案 0 :(得分:2)

您可以使用linq-to-xml。试试这段代码

var xmlString = "<?xml version=\"1.0\" encoding=\"utf-16\"?><MyClass><Id>1</Id><Names><string>Surya</string><string>Kiran</string></Names><ClassTypes><Types><TypeId>1</TypeId><TypeName>First Name</TypeName></Types><Types><TypeId>2</TypeId><TypeName>Last Name</TypeName></Types></ClassTypes><Status>1</Status></MyClass>";
XDocument doc = XDocument.Parse(xmlString);
XNode xNode = doc.FirstNode;
var jsonString = Newtonsoft.Json.JsonConvert.SerializeXNode(xNode, Newtonsoft.Json.Formatting.Indented, true);

Json字符串将是这个

{
  "Id": "1",
  "Names": {
    "string": [
      "Surya",
      "Kiran"
    ]
  },
  "ClassTypes": {
    "Types": [
      {
        "TypeId": "1",
        "TypeName": "First Name"
      },
      {
        "TypeId": "2",
        "TypeName": "Last Name"
      }
    ]
  },
  "Status": "1"
}

<强>更新

由于OP已经用类更新了问题,因此这是替代方法。

您可以使用此代码

获取格式正确的JSON
var xmlString = "<?xml version=\"1.0\" encoding=\"utf-16\"?><MyClass><Id>1</Id><Names><string>Surya</string><string>Kiran</string></Names><ClassTypes><Types><TypeId>1</TypeId><TypeName>First Name</TypeName></Types><Types><TypeId>2</TypeId><TypeName>Last Name</TypeName></Types></ClassTypes><Status>1</Status></MyClass>";
var myClassObject = XmlDeserializeData<MyClass>(xmlString);
var jsonString = JsonSerializeData(myClassObject);

以下是我的通用序列化/反序列化方法:

//using System.Xml.Serialization;
public T XmlDeserializeData<T>(string data)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(data);
    T result = (T)serializer.Deserialize(reader);
    return result;
}

//using Newtonsoft.Json
public string JsonSerializeData<T>(T data) 
{
    var serializedData = Newtonsoft.Json.JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented, new Newtonsoft.Json.Converters.StringEnumConverter());
    return serializedData; //notice the new Newtonsoft.Json.Converters.StringEnumConverter() to serialize enum as string
}

但是,在此之前,您需要在班级中进行以下更改

public class MyClass
{
    public int Id { get; set; }
    public List<string> Names { get; protected set; } //notice I changed from IList to List
    public List<Types> ClassTypes { get; protected set; } //IList doesn't work out of the box
    public StatusType Status { get; set; }

    public MyClass()
    {
        Names = new List<string>();
        ClassTypes = new List<Types>();
        Status = StatusType.Active;
    }
}

public enum StatusType //notice I added XmlEnum attribute, to serialize as 0, 1
{
    [XmlEnum(Name = "0")]
    Active = 0,
    [XmlEnum(Name = "1")]
    InActive = 1
}

这是生成的JSON

{
  "Id": 1,
  "Names": [
    "Surya",
    "Kiran"
  ],
  "ClassTypes": [
    {
      "TypeId": 1,
      "TypeName": "First Name"
    },
    {
      "TypeId": 2,
      "TypeName": "Last Name"
    }
  ],
  "Status": "InActive"
}

更新2

由于您无法更改类,并且您的XML不是“理想的”,因此您可以执行以下操作来获取所需的JSON。

var xmlString = "<?xml version=\"1.0\" encoding=\"utf-16\"?><MyClass><Id>1</Id><Names><string>Surya</string><string>Kiran</string></Names><ClassTypes><Types><TypeId>1</TypeId><TypeName>First Name</TypeName></Types><Types><TypeId>2</TypeId><TypeName>Last Name</TypeName></Types></ClassTypes><Status>1</Status></MyClass>";

xmlString = xmlString.Replace("<ClassTypes>", "")
                    .Replace("</ClassTypes>", "")
                    .Replace("<Names>", "")
                    .Replace("</Names>", "");

xmlString = xmlString.Replace("<Types>", "<ClassTypes>")
            .Replace("</Types>", "</ClassTypes>")
            .Replace("<string>", "<Names>")
            .Replace("</string>", "</Names>");

var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);

var xmlNode = xmlDoc.SelectNodes("//MyClass").Item(0);
var jsonString = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmlNode, Newtonsoft.Json.Formatting.Indented, true);

注意它会生成所需的json,但这是一个丑陋的黑客!应该使用以前的任何一种方法。