模型到 LazyMap

Model to LazyMap

我如何convert/deserialize这些模型

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

您可以使用 jackson-databind。例如

@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']]

如果您正在寻找快速破解方法,可以尝试类似的方法

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())

虽然快速破解的问题是你忘记了它们在以后崩溃时很快,并且只剩下一个破解 ;-)