问题
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