Grails JSONBuilder

Grails JSONBuilder,第1张

Grails JSONBuilder

我终于想出了如何使用来执行此 *** 作

JSONBuilder
,这是代码

import grails.web.*class JSonSerializer {    def target    String getJSON() {        Closure jsonFormat = { object = {     // Set the delegate of buildJSON to ensure that missing methods called thereby are routed to the JSonBuilder     buildJSON.delegate = delegate     buildJSON(target) }        }        def json = new JSonBuilder().build(jsonFormat)        return json.toString(true)    }    private buildJSON = {obj ->        obj.properties.each {propName, propValue -> if (!['class', 'metaClass'].contains(propName)) {     if (isSimple(propValue)) {         // It seems "propName = propValue" doesn't work when propName is dynamic so we need to         // set the property on the builder using this syntax instead         setProperty(propName, propValue)     } else {         // create a nested JSON object and recursively call this function to serialize it         Closure nestedObject = {  buildJSON(propValue)         }         setProperty(propName, nestedObject)     } }        }    }       private boolean isSimple(propValue) {        // This is a bit simplistic as an object might very well be Serializable but have properties that we want        // to render in JSON as a nested object. If we run into this issue, replace the test below with an test        // for whether propValue is an instanceof Number, String, Boolean, Char, etc.        propValue instanceof Serializable || propValue == null    }}

您可以通过将上面的代码和以下代码粘贴到 grails 控制台中进行测试

// Define a class we'll use to test the builderclass Complex {    String name    def nest2 =  new Expando(p1: 'val1', p2: 'val2')    def nest1 =  new Expando(p1: 'val1', p2: 'val2')}// test the classnew JSonSerializer(target: new Complex()).getJSON()

它应生成以下输出,该输出将的序列化实例存储

Complex
object
属性的值:

{"object": {   "nest2": {      "p2": "val2",      "p1": "val1"   },   "nest1": {      "p2": "val2",      "p1": "val1"   },   "name": null}}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5642519.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存