【问题标题】:Groovy JsonOutput/JsonBuilder issue with ValidatableValidatable 的 Groovy JsonOutput/JsonBuilder 问题
【发布时间】:2022-01-19 06:59:59
【问题描述】:

试图为继承自 trait grails.validation.Validateable 的类的简单对象获取 JsonOutput.toJson(obj) 结果:

    class Test implements Validateable{
        Long id 
    }

并抛出stackOverflow 异常。

同时对于以下纯类对象:

    class TestSimple {
        Long id 
    }

一切正常。

也用JsonBuilder 测试过,结果是一样的。有没有办法解决这个问题?

【问题讨论】:

标签: json grails groovy


【解决方案1】:

似乎Validateable trait 添加的某些属性在序列化为 json 时会导致递归调用链。我在这里没有完整的根本原因分析,但在 groovy >= 2.5.0 中,您可以执行以下操作:

import grails.validation.*
import groovy.json.*


class Abcdefg implements Validateable {
}

def a = new Abcdefg()

/* 
properties returned by DefaultGroovyMethods.getProperties(a):
  contentHash -> 25e8e25d2e2db8d4c1c300b2dbc5b75c
  originalClassName -> Abcdefg
  class -> class Abcdefg
  errors -> grails.validation.ValidationErrors: 0 errors
  constraintsMap -> [contentHash:grails.validation.ConstrainedDelegate@75561c4c, originalClassName:grails.validation.ConstrainedDelegate@771ff7d2]
*/
def generator = new groovy.json.JsonGenerator.Options()
    .excludeFieldsByName('errors', 'constraintsMap')
    .build()

def json = generator.toJson(a)

println(json)

从 json 序列化中排除 errorsconstraintsMap 属性并删除 StackOverflowException。

假设您不需要特别序列化 errorsconstraintsMap,这可能是一个选项。

如果你这样做了,你就必须深入挖掘并理解为什么会发生这种情况。

【讨论】:

    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    相关资源
    最近更新 更多