使用JSON.Net将XML转换为JSON字符串时没有得到期望的结果



下面是我们正在尝试转换为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);
实际结果

{" Id ": " 1 ", "名称":{"字符串":["苏利耶"、"Kiran"]},"ClassTypes":{"类型":[{"类型Id":"1","TypeName":"首先名称"},{"类型id":"2","TypeName":"姓"}]},"状态":"1"}

预期的结果

{" Id ": 1、"名称":"亚"、"Kiran","ClassTypes":[{"类型Id":1、"TypeName":"首先"类型id"名称"},{:2,"TypeName":"姓"}],"状态":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
}

您可以使用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,但这是一个丑陋的hack!

相关内容

  • 没有找到相关文章