[英]Convert LinkedHashMap<String,String> to an object in Java
[英]How to convert LinkedHashMap to Map<String, Object> in Java?
我正在尝试将地图转换为地图。 我有一个json和Object:
{
A: { availableInfo: { isAvailable : true} },
VV: { availableInfo: { isAvailable : false} },
B45: { availableInfo: { isAvailable : null} }
}
和对象:
@Builder
@Getter
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class AvailableInfo {
@JsonProperty("isAvailable")
private Boolean isAvailable;
public AvailableInfo() {
}
}
我试过了 :
Map<String, AvailableInfo> response = getResponse(query, Map.class);
但我得到错误:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to AvailableInfo
下面是getResponse()方法:
private <T> T getResponse(final RestURI query, final Class<T> responseClass) throws IOException {
T response = null;
final RestResponse<Record> tempResponse = client.call(GET, query);
if (isResponseOK(tempResponse, query)) {
byte[] payloads = {};
for (Record rec : tempResponse.getResponses()) {
final byte[] payload = rec.getPayload();
payloads = ArrayUtils.addAll(payloads, payload);
}
final Reader reader = newReader(payloads)
response = jsonObjectMapper.readValue(reader, responseClass);
}
return response; //returns Map<String, LinkedHashMap>
}
知道如何解决吗? 我尝试将输入json更改为:
{
A: { isAvailable : true} ,
VV: { isAvailable : false} ,
B45: { isAvailable : null}
}
但仍然无法正常工作。
尝试将您的方法签名更改为
private <T> T getResponse(final RestURI query, final TypeReference typeReference) throws IOException {
T response = null;
final RestResponse<Record> tempResponse = client.call(GET, query);
if (isResponseOK(tempResponse, query)) {
byte[] payloads = {};
for (Record rec : tempResponse.getResponses()) {
final byte[] payload = rec.getPayload();
payloads = ArrayUtils.addAll(payloads, payload);
}
final Reader reader = newReader(payloads)
response = jsonObjectMapper.readValue(reader, typeReference);
}
return response; //returns Map<String, AvailableInfo>
}
并以以下方式调用
TypeReference typeReference = new TypeReference<Map<String, AvailableInfo>>() {
};
Map<String, AvailableInfo> map = (Map<String, AvailableInfo>) getResponse(typeReference);
使用以下json示例
{
A: { isAvailable : true} ,
VV: { isAvailable : false} ,
B45: { isAvailable : null}
}
我尝试过并为我工作
首先使用下面的行将其转换,然后就可以使用数据了:
List<? extends Map<String, String>> resultList = new ArrayList<LinkedHashMap<String, String>>();
要将json转换为Map,json必须采用以下形式:
{
A: { isAvailable : true} ,
VV: { isAvailable : false} ,
B45: { isAvailable : null}
}
之后,以下代码返回Map<String, AvailableInfo>
:
Map<String, AvailableInfo> readValue = mapper.readValue(json, Map.class);
System.out.println(readValue);
输出System.out.println(readValue);
:
{A={isAvailable=true}, VV={isAvailable=false}, B45={isAvailable=null}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.