简体   繁体   English

JSON到XML,C#中单个对象一行

[英]JSON to XML, and one row for single object in C#

I am looking for a conversion from JSON objects to XML single row for each object. 我正在寻找每个对象从JSON objectsXML single row的转换。 Right now, I am able to convert to XML but, that is not I desired. 现在,我能够转换为XML,但这不是我想要的。 Can somebody assist me? 有人可以帮我吗? Also, I don't need some of the fields. 另外,我不需要某些字段。 Here are the JSON and preferred XML structure . 这是JSON and preferred XML structure

Example of JSON JSON范例

{
   "paging": {
      "limit": 100,
      "total": 1394,
      "next": "Mg=="
   },
   "data": [
      {
         "mmsi": 538006090,
         "imo": 9700665,
         "last_known_position": {
            "timestamp": "2017-12-18T20:24:27+00:00",
            "geometry": {
               "type": "Point",
               "coordinates": [
                  60.87363,
                  -13.02203
               ]
            }
         }
      },
      {
         "mmsi": 527555481,
         "imo": 970000,
         "last_known_position": {
            "timestamp": "2017-12-18T20:24:27+00:00",
            "geometry": {
               "type": "Point",
               "coordinates": [
                  4.57883,
                  3.76899
               ]
            }
         }
      }
   ]
}

The XML that I desired 我想要的XML

<vessel>
     <row mmsi="538006090" imo="9700665" lat="60.87363" lon="-13.02203"/>
     <row mmsi="527555481" imo="970000" lat="4.57883" lon="3.76899"/>
</vessel>

Thank you 谢谢

A standard JSON-to-XML conversion library will never give you exactly the XML that you want; 标准的JSON到XML转换库将永远不会为您提供所需的XML。 you will nearly always want to follow it with a transformation of that XML using XSLT. 您几乎总是希望使用XSLT对XML进行转换。

The alternative is to hand-construct the XML that you want from the original JSON. 另一种方法是从原始JSON手动构造所需的XML。

Both approaches are possible using XSLT 3.0 which I'm including for illustration purposes, but you could use the same design approach with other languages. 包括XSLT 3.0在内,这两种方法都是可能的,出于说明目的,我将其包括在内,但是您可以将相同的设计方法用于其他语言。

(a) If you do a standard json-to-xml conversion using XSLT 3.0, it will give you an XML structure like this: (a)如果使用XSLT 3.0执行标准的json到xml转换,它将为您提供如下XML结构:

<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
   <map key="paging">
      <number key="limit">100</number>
      <number key="total">1394</number>
      <string key="next">Mg==</string>
   </map>
   <array key="data">
      <map>
         <number key="mmsi">538006090</number>
         <number key="imo">9700665</number>
         <map key="last_known_position">
            <string key="timestamp">2017-12-18T20:24:27+00:00</string>
            <map key="geometry">
               <string key="type">Point</string>
               <array key="coordinates">
                  <number>60.87363</number>
                  <number>-13.02203</number>
               </array>
            </map>
         </map>
      </map>
      <map>
         <number key="mmsi">527555481</number>
         <number key="imo">970000</number>
         <map key="last_known_position">
            <string key="timestamp">2017-12-18T20:24:27+00:00</string>
            <map key="geometry">
               <string key="type">Point</string>
               <array key="coordinates">
                  <number>4.57883</number>
                  <number>3.76899</number>
               </array>
            </map>
         </map>
      </map>
   </array>
</map>

which you can then transform to your desired output using: 然后可以使用以下命令将其转换为所需的输出:

<xsl:template name="postprocess" xpath-default-namespace=""http://www.w3.org/2005/xpath-functions">
  <vessel>
    <xsl:for-each select=".//map[number[@key='mmsi']]">
       <row mmsi="{*[@key='mmsi']}" 
            imo="*[@key='imo']" 
            lat="{.//*[@key='coordinates']/number[1]}" 
            lon="{.//*[@key='coordinates']/number[1]}"/>
    </xsl:for-each>
  </vessel>
</xsl:template>

(b) Alternatively, and perhaps more easily in this case, you can pick out the parts of the JSON that you want and construct the XML directly: (b)另外,在这种情况下,也许更容易,您可以选择所需的JSON部分并直接构造XML:

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="#all"
  version="3.0">

  <xsl:template name="xsl:initial-template">
    <vessel>
      <xsl:for-each select="json-doc('test.json')?data?*">
        <xsl:variable name="coords" select="?last_known_position?geometry?coordinates"/>
        <row mmsi="{xs:integer(?mmsi)}" imo="{xs:integer(?imo)}" lat="{$coords?1}" lon="{$coords?2}"/>
      </xsl:for-each>
    </vessel>
  </xsl:template>  

</xsl:transform>

With Cinchoo ETL - an open source library, you can do do the conversion easily with few lines of code 使用Cinchoo ETL-一个开源库,您只需几行代码即可轻松完成转换

string json = @"{
    ""paging"": {

        ""limit"": 100,
        ""total"": 1394,
        ""next"": ""Mg==""
    },
    ""data"": [
        {
            ""mmsi"": 538006090,
            ""imo"": 9700665,
            ""last_known_position"": {
            ""timestamp"": ""2017-12-18T20:24:27+00:00"",
            ""geometry"": {
                ""type"": ""Point"",
                ""coordinates"": [
                    60.87363,
                    -13.02203
                ]
    }
}
        },
        {
            ""mmsi"": 527555481,
            ""imo"": 970000,
            ""last_known_position"": {
            ""timestamp"": ""2017-12-18T20:24:27+00:00"",
            ""geometry"": {
                ""type"": ""Point"",
                ""coordinates"": [
                    4.57883,
                    3.76899
                ]
            }
            }
        }
    ]
}
";
StringBuilder sb = new StringBuilder();
using (var p = ChoJSONReader.LoadText(json)
    .WithJSONPath("$..data")
    )
{
    using (var w = new ChoXmlWriter(sb)
        .Configure(c => c.RootName = "vessel")
        .Configure(c => c.NodeName = "row")
        )
    {
        w.Write(p.Select(r => new { _mmsi = r.mmsi, _imo = r.imo, _lat = r.last_known_position.geometry.coordinates[0], _lon = r.last_known_position.geometry.coordinates[1] }));
    }
}
Console.WriteLine(sb.ToString());

Output: 输出:

<vessel>
  <row mmsi="538006090" imo="9700665" lat="60.87363" lon="-13.02203" />
  <row mmsi="527555481" imo="970000" lat="4.57883" lon="3.76899" />
</vessel>

Checkout CodeProject article for some additional help. 查阅CodeProject文章以获取其他帮助。

UPDATE: 更新:

To handle special null value condition, you can write as below 要处理特殊的空值条件,可以编写如下

string json = @"{
    ""paging"": {

        ""limit"": 100,
        ""total"": 1394,
        ""next"": ""Mg==""
    },
    ""data"": [
        {
            ""mmsi"": 538006090,
            ""imo"": 9700665,
            ""last_known_position"": {
            ""timestamp"": ""2017-12-18T20:24:27+00:00"",
            ""geometry"": {
                ""type"": ""Point"",
                ""coordinates"": [
                    60.87363,
                    -13.02203
                ]
    }
}
        },
        {
            ""mmsi"": 527555481,
            ""imo"": null,
            ""last_known_position"": {
            ""timestamp"": ""2017-12-18T20:24:27+00:00"",
            ""geometry"": {
                ""type"": ""Point"",
                ""coordinates"": [
                    4.57883,
                    3.76899
                ]
            }
            }
        }
    ]
}
";
StringBuilder sb = new StringBuilder();
using (var p = ChoJSONReader.LoadText(json)
    .WithJSONPath("$..data")
    )
{
    using (var w = new ChoXmlWriter(sb)
        .Configure(c => c.RootName = "vessel")
        .Configure(c => c.NodeName = "row")
        )
    {
        w.Write(p.Select(r => new { _mmsi = r.mmsi, _imo = r.imo == null ? "null" : r.imo, _lat = r.last_known_position.geometry.coordinates[0], _lon = r.last_known_position.geometry.coordinates[1] }));
    }
}
Console.WriteLine(sb.ToString());

Output: 输出:

<vessel>
  <row mmsi="538006090" imo="9700665" lat="60.87363" lon="-13.02203" />
  <row mmsi="527555481" imo="null" lat="4.57883" lon="3.76899" />
</vessel>

Disclaimer: I'm the author of this library. 免责声明:我是这个图书馆的作者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM