首页 新闻 会员 周边

【json.net】xml转换为json格式时,如何将指定节点转换成数组

0
[已解决问题] 解决于 2012-10-19 08:42
1 using System.Xml.Linq;
2 using Newtonsoft.Json;
3 
4 
5 Response.ContentType = "application/json";
6 
7 XDocument xdoc = XDocument.Load(path);
8 
9 Response.Write(JsonConvert.SerializeXNode(xdoc));

 

xml 片段 :

<specialty nameCN="电测">
        <step>
            <signer staffID="800706" nameCN=""><![CDATA[]]></signer>
        </step>
        <step>
            <signer staffID="090477" nameCN=""><![CDATA[]]></signer>
        </step>
    </specialty>
    <specialty nameCN="节能">
        <step>
            <signer staffID="800608" nameCN=""><![CDATA[]]></signer>
            <signer staffID="800808" nameCN=""><![CDATA[]]></signer>
        </step>
        <step>
            <signer staffID="800602" nameCN=""><![CDATA[]]></signer>
            <signer staffID="800803" nameCN=""><![CDATA[]]></signer>
        </step>
    </specialty>

 //输出 json 结果

{
  "@nameCN": "电测",
  "step": [
    {
      "signer": {
        "@staffID": "800706",
        "@nameCN": "",
        "#cdata-section": 
      }
    },
    {
      "signer": {
        "@staffID": "090477",
        "@nameCN": "",
        "#cdata-section": 
      }
    }
  ]
},
{
  "@nameCN": "节能",
  "step": [
    {
      "signer": [
        {
          "@staffID": "800608",
          "@nameCN": "",
          "#cdata-section": 
        },
        {
          "@staffID": "800808",
          "@nameCN": "",
          "#cdata-section": 
        }
      ]
    },
    {
      "signer": [
        {
          "@staffID": "800602",
          "@nameCN": "",
          "#cdata-section": 
        },
        {
          "@staffID": "800803",
          "@nameCN": "",
          "#cdata-section": 
        }
      ]
    }
  ]
}

 

 

上面的结果 用红色标记出来的就是差别,step下有多个signer节点时,输出结果signer是数组

只有1个signer节点 输出signer不是数组如何在只有一个signer节点时也输出为数组

readonly的主页 readonly | 菜鸟二级 | 园豆:406
提问于:2012-09-27 15:53
< >
分享
最佳答案
1

有一个方案,但不在好,也就是把xml先反序列化,反序列化时要写类来反序列化,然后再序列化成json。

另一个就是xsd,但我不熟,不知道能不能实现。

奖励园豆:5
空明流光 | 初学一级 |园豆:106 | 2012-09-27 16:05

嗯,3Q,第一个方案我想过,先把xml转换为对象,在对象中signer可对应成集合,

然后用 JsonConvert.SerializeObject()就可以。

 

图方便我用另一中方法解决的,在客户端转换,判断signer是否是数组,如果不是就设置成数组

ko.utils.arrayForEach(res.workflow.specialty, function (sp) {
    ko.utils.arrayForEach(sp.step, function (step) {
        //$.isArray(step.signer)
        if (Object.prototype.toString.apply(step.signer) !== '[object Array]') {
            step.signer = [step.signer];
        }
    });
});

 

JsonConvert.SerializeXNode()只有3个重载方法,不知道还有没有其他设置的方法

readonly | 园豆:406 (菜鸟二级) | 2012-09-27 16:30
其他回答(1)
1

同遇到这个问题,刚搜到 留后观,添加xml属性 json:Array=true

http://stackoverflow.com/questions/21382879/xml-to-json-using-newtonsoft-issue-when-loop-over-array-of-one-element/21383423#21383423

xingchen517 | 园豆:202 (菜鸟二级) | 2015-11-09 14:03
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册