简体   繁体   English

Grails / Groovy向现有Java类添加属性,而在尝试使用JSON转换器进行序列化时丢失它们?

[英]Grails/Groovy adding properties to existing Java class, losing them when trying to serialize using JSON converter?

i am wondering what i am missing in adding dynamic properties to a java class and trying to render that class using the JSON converter. 我想知道在向Java类中添加动态属性并尝试使用JSON转换器呈现该类时所缺少的东西。 I have a pure java pojo and i am adding a dynamic property to it using: 我有一个纯净的Java pojo,并使用以下方法为其添加了动态属性:

// adding property
ResetRequest.metaClass.targetIp = "192.168.0.1"
// creating object
ResetRequest obj = new ResetRequest()
// printing the properties
println obj.properties

When printing the properties the object has a additional property called 'targetIp' so all seems ok, but when i try to render the object as JSON the added property is not in the JSON string. 在打印属性时,该对象还有一个名为“ targetIp”的附加属性,因此看起来一切正常,但是当我尝试将对象呈现为JSON时,添加的属性不在JSON字符串中。

Any suggestion what i am missing. 任何建议,我想念的。

I think the JSON conversion in grails does not pick up dynamically added properties. 我认为grails中的JSON转换不会获取动态添加的属性。

Maybe you should register your own object marshaller for the class in question? 也许您应该为相关课程注册自己的对象编组?

In Bootstrap: 在引导程序中:

    def init = {servletContext ->
        JSON.registerObjectMarshaller(ResetRequest) {req->
            [
                targetIp:req.targetIp
                //etc 
            ]
    }

UPDATE This link shows how you can inherit from the default Marshaller and add your own logic to marshall specific fields: UPDATE此链接显示如何继承默认的Marshaller并添加自己的逻辑以编组特定字段:

http://grails4you.com/2012/04/restful-api-for-grails-domains/ http://grails4you.com/2012/04/restful-api-for-grails-domains/

You should register custom property in Bootstrap like 您应该在Bootstrap中注册自定义属性,例如

def init = { servletContext ->
  ResetRequest.metaClass.targetIp = {req ->
    return "192.168.0.1";   
  } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM