如何转换/反序列化这些模型
public class AccessCredentials {
String userName = ''
String password = ''
LoginOptions loginOptions = new LoginOptions()
}
public class LoginOptions {
String partnerId = ''
String applicationId = ''
}
进入LazyMap,如:
[
userName : userName,
password : password,
loginOptions : [
partnerId : partnerId,
applicationId : applicationId
]
]
答案 0 :(得分:1)
您可以使用jackson-databind。 E.g。
@Grab('com.fasterxml.jackson.core:jackson-databind:2.5.4')
import com.fasterxml.jackson.databind.ObjectMapper
class AccessCredentials {
String userName = 'Between The Buried And Me'
String password = 'Alaska'
LoginOptions loginOptions = new LoginOptions()
}
class LoginOptions {
String partnerId = 'Colors'
String applicationId = 'The Great Misdirect'
}
def mapper = new ObjectMapper()
assert mapper.convertValue(new AccessCredentials(), Map) == ['userName':'Between The Buried And Me', 'password':'Alaska', 'loginOptions':['partnerId':'Colors', 'applicationId':'The Great Misdirect']]
答案 1 :(得分:1)
如果你正在寻找快速黑客,你可以尝试这样的事情
def objectMapper(o) {
o.class.declaredFields.findAll { !it.synthetic }.collectEntries {
switch(o."$it.name".class.name) {
case ~/^java\..*/:
case ~/^javax\..*/:
case ~/^com\.sun\..*/:
case ~/^sun\..*/:
return [(it.name):o."$it.name"]
default:
return [(it.name):objectMapper(o."$it.name")]
}
}
}
objectMapper(new AccessCredentials())
虽然快速黑客的问题是你忘记了他们在以后休息时很快就会被打破,并且只是留下了黑客; - )