【问题标题】:how to put pretty JSON into REST api如何将漂亮的 JSON 放入 REST api
【发布时间】:2016-02-28 09:22:17
【问题描述】:

我正在尝试构建一个接受 XML 的 REST 服务并将其转换为 JSON 并调用接受 JSON 的外部服务并将我的 JSON 放入其中。我可以把 json 放在没有漂亮的地方,但我想把 json 放在漂亮的格式中。请建议怎么做,下面是我的代码...

package com.mypackge

import grails.converters.JSON
import grails.rest.RestfulController
import grails.plugins.rest.client.RestBuilder

class RestCustomerController extends RestfulController {
/*
    static responseFormats = ['json', 'xml']
    RestCustomerController() {
    super(Customer)
    }
*/
    def index() {
        convertXmlToJson()
    }

    def myJson = ''

    def convertXmlToJson() {
    def xml = ''' <Customer>
            <customerid>9999999999999</customerid>
            <ssn>8888</ssn>
            <taxid>8888</taxid>
            <address>
                            <addressline1>Yamber Ln</addressline1>
                            <addressline1>8664 SE</addressline1>
                            <city>CCCCC</city>
                            <state>CC</state>
                            <zipcode>97679</zipcode>
            </address>
            <firstname>Scott</firstname>
            <middlename></middlename>
            <lastname>David</lastname>
            <account>
                                            <accountno>576-294738943</accountno>
                                            <accounttype>Lease</accounttype>
                                            <accountsubtype></accountsubtype>
                                            <accountstatus>complete</accountstatus>
                                            <firstname>Scott</firstname>
                                            <middlename></middlename>
                                            <lastname>David</lastname>
                                            <businessname></businessname>
                                            <billingsystem>yoiuhn</billingsystem>
                                            <brand></brand>
                                            <plantype></plantype>
                                            <billingaddress>
                                                            <addressline1>Yamber Ln</addressline1>
                                                            <addressline1>8664 SE </addressline1>
                                                            <city>CCCCC</city>
                                                            <state>CC</state>
                                                            <zipcode>97679</zipcode>
                                            </billingaddress>
                                            <job>
                                                            <jobid>8276437463728</jobid>
                                                            <jobstatus>SUCCESS</jobstatus>
                                            </job>
            </account>
            </Customer>
            '''.stripMargin()

        // Parse it
            def parsed = new XmlParser().parseText( xml )

            def myId = parsed.customerid.text()
            // Deal with each node:
            def handle
            handle = { node ->
                if( node instanceof String ) {
                node
                }
                else {
                    [ (node.name()): node.collect( handle ) ]
                }
            }
            // Convert it to a Map containing a List of Maps
            def jsonObject = [ (parsed.name()): parsed.collect { node ->
                            [ (node.name()): node.collect( handle ) ]
                            } ]
            def json = new groovy.json.JsonBuilder(jsonObject) //.toPrettyString()
            // Check it's what we expected
            def mmyresp
                try{
                    mmyresp = putRequest(myId,json)
                }catch(Exception e) {
                    mmyresp = 'Please Validate JSON ....'
                }
    }

    def putRequest(String id, JSON myJson) {
            String url = "http://foo.com/customer/external/"+id
            def rest = new RestBuilder()
            def resp = rest.put(url){
                contentType "application/json"
                json{
                myJson
                }
            }
            return resp
    }

}

记录按以下格式添加...

{"Customer":[{"customerid":["9999999999999"]},{"ssn":["8888"]},
{"taxid":["8888"]},{"address":[{"addressline1":["Yamber Ln"]},
{"addressline1":["8664 SE"]},{"city":["CCCCC"]},{"state":["CC"]},{"zipcode":["97679"]}]},
{"firstname":["Scott"]},{"middlename":[]},{"lastname":["David"]},{"businessname":[]},
{"account":[{"accountno":["576-294738943"]},{"accounttype":["Lease"]},{"accountsubtype":[]},
{"accountstatus":["complete"]},{"firstname":["Scott"]},{"middlename":[]},{"lastname":["David"]},
{"businessname":[]},{"billingsystem":["yoiuhn"]},{"brand":[]},{"plantype":[]},
{"billingaddress":[{"addressline1":["Yamber Ln"]},{"addressline1":["8664 SE"]},
{"city":["CCCCC"]},{"state":["CC"]},{"zipcode":["97679"]}]},{"job":[{"jobid":["8276437463728"]},
,{"jobstatus":["SUCCESS"]}]}]}]}

但我希望它以漂亮的格式插入。我尝试了.toPrettyString(),但在尝试作为 json 放置时出现了强制转换异常。我是第一次尝试 REST 服务,不知道我在哪里做错了。请就此向我提出建议。

【问题讨论】:

    标签: json web-services rest grails


    【解决方案1】:

    您应该在Config.groovy中设置以下字段。

    grails.converters.default.pretty.print = true

    这对于 xml 和 json 都会很好地打印出来。

    您可以选择为 xml 或 json 设置它,如下所示:

    对于 json

    grails.converters.json.pretty.print = true

    对于 xml

    grails.converters.xml.pretty.print = true

    Config.groovy 条目的示例是:

    environments {
        development {
            grails.converters.json.pretty.print = true 
        }
     } 
    

    希望对你有帮助!!!

    【讨论】:

      【解决方案2】:

      对于 Grails 4,试试这个:

      def json = x as JSON
      json.prettyPrint = true;
      log.info(json.toString())
      

      【讨论】:

        猜你喜欢
        • 2015-10-23
        • 2020-11-21
        • 1970-01-01
        • 2021-06-02
        • 1970-01-01
        • 2021-08-26
        • 1970-01-01
        • 2014-12-13
        • 2014-05-19
        相关资源
        最近更新 更多