Groovy - XML to JSON without knowing each key

别说谁变了你拦得住时间么 提交于 2019-12-24 02:59:11

问题


I have an XML web service response (see below) and would like to convert it to JSON, without knowing each key.

The response is much bigger, this is just a sample showing the structure.

Is this possible to do in Groovy?

<allMortProdContainers>
   <WsMortProdContainerv02>
      <allWsMortProdCapCollarBandByEnd xsi:nil="true"/>
      <allWsMortProdCashBackBandByEnd xsi:nil="true"/>
      <allWsMortProdEarlyRepaymentBandByEnd>
         <WsMortProdEarlyRepaymentBandv01>
            <endDate>???</endDate>
            <endMonth>???</endMonth>
            <fixedCharge>???</fixedCharge>
            <monthsInterest>???</monthsInterest>
            <percentage>???</percentage>
         </WsMortProdEarlyRepaymentBandv01>
      </allWsMortProdEarlyRepaymentBandByEnd>
      <myWsMortProdSpec>
         <productBaseRate>???</productBaseRate>
         <productBaseRateDescription>???</productBaseRateDescription>
         <productCode>???</productCode>
         <productDescription>???</productDescription>
         <productDescriptionWebFriendly>???</productDescriptionWebFriendly>
         <productInfoKey>???</productInfoKey>
         <productType>???</productType>
      </myWsMortProdSpec>
   </WsMortProdContainerv02>
</allMortProdContainers>

回答1:


@Grab(group='org.json', module='json', version='20180130')
import org.json.XML;

def xml = '''<allMortProdContainers xmlns:xsi="...." >
   <WsMortProdContainerv02>
      <allWsMortProdCapCollarBandByEnd xsi:nil="true"/>
      <allWsMortProdCashBackBandByEnd xsi:nil="true"/>
      <allWsMortProdEarlyRepaymentBandByEnd>
         <WsMortProdEarlyRepaymentBandv01>
            <endDate>???</endDate>
            <endMonth>???</endMonth>
            <fixedCharge>???</fixedCharge>
            <monthsInterest>???</monthsInterest>
            <percentage>???</percentage>
         </WsMortProdEarlyRepaymentBandv01>
      </allWsMortProdEarlyRepaymentBandByEnd>
      <myWsMortProdSpec>
         <productBaseRate>???</productBaseRate>
         <productBaseRateDescription>???</productBaseRateDescription>
         <productCode>???</productCode>
         <productDescription>???</productDescription>
         <productDescriptionWebFriendly>???</productDescriptionWebFriendly>
         <productInfoKey>???</productInfoKey>
         <productType>???</productType>
      </myWsMortProdSpec>
   </WsMortProdContainerv02>
</allMortProdContainers>'''

println XML.toJSONObject(xml).toString(2)


来源:https://stackoverflow.com/questions/50838938/groovy-xml-to-json-without-knowing-each-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!