Groovy-从XML到JSON,无需知道每个键 [英] Groovy - XML to JSON without knowing each key

查看:148
本文介绍了Groovy-从XML到JSON,无需知道每个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML Web服务响应(请参见下文),并希望将其转换为JSON,而无需知道每个键.

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.

在Groovy中可以这样做吗?

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>

推荐答案

@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)

这篇关于Groovy-从XML到JSON,无需知道每个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆