栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Grails JSONBuilder

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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}}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636686.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号