我正在尝试将地图从http响应转换为POJO。回复是
{_total=0}
在我的Pojo中,我想摆脱下划线,所以我用@JsonProperty注释了该字段。但是Groovy抱怨没有_total属性
堆栈跟踪
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '{_total=0}' with class 'java.util.LinkedHashMap' to class 'io.toro.linkedin.response.CompanyAdminsResponse' due to: org.codehaus.groovy.runtime.metaclass.MissingPropertyExceptionNoStack: No such property: _total for class: io.toro.linkedin.response.CompanyAdminsResponse
Possible solutions: total
at io.toro.linkedin.connector.LinkedInConnector.linkedInListCompaniesThatUserIsAdminOf(LinkedInConnector.groovy:314)
at LinkedInTest.list-companies-that-user-is-admin-of(LinkedInTest.groovy:115)
转换代码
HttpResponseDecorator response = restClient.get(params)
ObjectMapper mapper = new ObjectMapper()
mapper.convertValue(response.data as Map, T)
POJO
package io.toro.linkedin.response
import com.fasterxml.jackson.annotation.JsonProperty
import groovy.transform.ToString
import io.toro.linkedin.model.Company
/**
* @author daniel.gomez
*/
@ToString(includeNames = true)
class CompanyAdminsResponse {
@JsonProperty('_count')
int count
@JsonProperty('_start')
int start
@JsonProperty('_total')
int total
List<Company> values
}
答案 0 :(得分:0)
我认为问题来自您对Map
的响应转换:response.data as Map
您传递给mapper.convertValue
方法。
我直接使用跟随Map
[_total : 3]
制作一个groovy脚本来测试您的问题,并且没有异常抛出正确创建的对象:
@Grab('com.fasterxml.jackson.core:jackson-core:2.7.3')
@Grab('com.fasterxml.jackson.core:jackson-annotations:2.7.3')
@Grab('com.fasterxml.jackson.core:jackson-databind:2.7.3')
@GrabExclude('org.codehaus.groovy:groovy-all')
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
import groovy.transform.ToString
class Company {
}
@ToString(includeNames = true)
class CompanyAdminsResponse {
@JsonProperty('_count')
int count
@JsonProperty('_start')
int start
@JsonProperty('_total')
int total
List<Company> values
}
ObjectMapper mapper = new ObjectMapper()
def object = [_total : 3]
println mapper.convertValue(object, CompanyAdminsResponse)
// the above line prints CompanyAdminsResponse(count:0, start:0, total:3, values:null)
希望这有帮助,