3

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>
Tom
  • 31
  • 2

1 Answers1

3
@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)
daggett
  • 26,404
  • 3
  • 40
  • 56