gpt4 book ai didi

java - Jruby on Rails java 对象序列化

转载 作者:行者123 更新时间:2023-12-01 05:48:10 25 4
gpt4 key购买 nike

亲爱的开发者你好我有一个 ruby​​ on Rails 项目,其中包含一些带有 java 库的特定逻辑。我想添加在 Controller 中为该对象渲染 json 和 xml 的可能性,就像 Activity 记录序列化一样。

我该怎么做?

Controller 中的代码示例

// Create the ContactWS structure
ContactWS contactInfo = new ContactWS();
// Put some data into it
contactInfo.setPostalCode("12345");
contactInfo.setFaxNumber("555-123456");
contactInfo.setEmail("foo@bar.com");
// Pass the contact info to the user creation call
// This assumes userData is an already filled UserWS structure.
userData.setContact(contactInfo);
// Now create the user
UserWS newUser = api.createUser(userData);

newUser 是具有私有(private)属性的 Java 值对象,并且 没有任何其他方法的 getter/setter

接下来我应该将此对象序列化为 json

最佳答案

对于 jruby google-gson 就可以了 http://code.google.com/p/google-gson/

示例

include_package "com.google.gson"
gson = GsonBuilder.new.setFieldNamingPolicy(FieldNamingPolicy::LOWER_CASE_WITH_UNDERSCORES).create()
json = gson.to_json(javaObject)

关于java - Jruby on Rails java 对象序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5388316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com