简体   繁体   English

java.lang.ClassCastException:java.util.LinkedHashMap 无法转换为 com.testing.models.Account

[英]java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

I'm getting below error:我收到以下错误:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

with below code用下面的代码

final int expectedId = 1;

Test newTest = create();

int expectedResponseCode = Response.SC_OK;

ArrayList<Account> account = given().when().expect().statusCode(expectedResponseCode)
    .get("accounts/" + newTest.id() + "/users")
    .as(ArrayList.class);
assertThat(account.get(0).getId()).isEqualTo(expectedId);

Is there a reason why I cannot do get(0) ?我不能做get(0)有什么原因吗?

The issue's coming from Jackson.问题来自杰克逊。 When it doesn't have enough information on what class to deserialize to, it uses LinkedHashMap .当它没有关于要反序列化到哪个类的足够信息时,它使用LinkedHashMap

Since you're not informing Jackson of the element type of your ArrayList , it doesn't know that you want to deserialize into an ArrayList of Account s.由于您没有将ArrayList的元素类型通知 Jackson,因此它不知道您想要反序列化为AccountArrayList So it falls back to the default.所以它回退到默认值。

Instead, you could probably use as(JsonNode.class) , and then deal with the ObjectMapper in a richer manner than rest-assured allows.相反,您可能可以使用as(JsonNode.class) ,然后以比放心允许的更丰富的方式处理ObjectMapper Something like this:像这样的东西:

ObjectMapper mapper = new ObjectMapper();

JsonNode accounts = given().when().expect().statusCode(expectedResponseCode)
    .get("accounts/" + newClub.getOwner().getCustId() + "/clubs")
    .as(JsonNode.class);


//Jackson's use of generics here are completely unsafe, but that's another issue
List<Account> accountList = mapper.convertValue(
    accounts, 
    new TypeReference<List<Account>>(){}
);

assertThat(accountList.get(0).getId()).isEqualTo(expectedId);

Try the following:请尝试以下操作:

POJO pojo = mapper.convertValue(singleObject, POJO.class);

or:或者:

List<POJO> pojos = mapper.convertValue(
    listOfObjects,
    new TypeReference<List<POJO>>() { });

See conversion of LinkedHashMap for more information.有关更多信息,请参阅LinkedHashMap 的转换

The way I could mitigate the JSON Array to collection of LinkedHashMap objects problem was by using CollectionType rather than a TypeReference .我可以减轻JSON 数组到 LinkedHashMap 对象集合问题的方法是使用CollectionType而不是TypeReference This is what I did and worked :这就是我所做的和工作的

public <T> List<T> jsonArrayToObjectList(String json, Class<T> tClass) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, tClass);
    List<T> ts = mapper.readValue(json, listType);
    LOGGER.debug("class name: {}", ts.get(0).getClass().getName());
    return ts;
}

Using the TypeReference , I was still getting an ArrayList of LinkedHashMaps, ie does not work :使用TypeReference ,我仍然得到 LinkedHashMaps 的 ArrayList,即不起作用

public <T> List<T> jsonArrayToObjectList(String json, Class<T> tClass) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    List<T> ts = mapper.readValue(json, new TypeReference<List<T>>(){});
    LOGGER.debug("class name: {}", ts.get(0).getClass().getName());
    return ts;
}

I had a similar exception (but different problem) - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.bson.Document , and fortunately it's solved easier:我有一个类似的异常(但不同的问题) - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.bson.Document ,幸运的是它更容易解决:

Instead of代替

List<Document> docs = obj.get("documents");
Document doc = docs.get(0)

which gives error on second line, One can use在第二行给出错误,可以使用

List<Document> docs = obj.get("documents");
Document doc = new Document(docs.get(0));

Solve problem with two method parse common用两种方法解析共同解决问题

  1. Whith type is an object类型是对象
public <T> T jsonToObject(String json, Class<T> type) {
        T target = null;
        try {
            target = objectMapper.readValue(json, type);
        } catch (Jsenter code hereonProcessingException e) {
            e.printStackTrace();
        }
    
        return target;
    }
  1. With type is collection wrap object类型是集合包装对象
public <T> T jsonToObject(String json, TypeReference<T> type) {
    T target = null;
    try {
        target = objectMapper.readValue(json, type);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return target;
}

I have this method for deserializing an XML and converting the type:我有这种反序列化 XML 和转换类型的方法:

public <T> Object deserialize(String xml, Class objClass ,TypeReference<T> typeReference ) throws IOException {
    XmlMapper xmlMapper = new XmlMapper();
    Object obj = xmlMapper.readValue(xml,objClass);
    return  xmlMapper.convertValue(obj,typeReference );   
}

and this is the call:这是电话:

List<POJO> pojos = (List<POJO>) MyUtilClass.deserialize(xml, ArrayList.class,new TypeReference< List< POJO >>(){ });

When you use jackson to map from string to your concrete class, especially if you work with generic type.当您使用 jackson 从字符串映射到具体类时,尤其是在使用泛型类型时。 then this issue may happen because of different class loader.那么这个问题可能会因为不同的类加载器而发生。 i met it one time with below scenarior:我遇到过一次以下场景:

Project B depend on Library A项目 B 依赖库 A

in Library A:在图书馆 A:

public class DocSearchResponse<T> {
 private T data;
}

it has service to query data from external source, and use jackson to convert to concrete class它具有从外部源查询数据的服务,并使用 jackson 转换为具体类

public class ServiceA<T>{
  @Autowired
  private ObjectMapper mapper;
  @Autowired
  private ClientDocSearch searchClient;

  public DocSearchResponse<T> query(Criteria criteria){
      String resultInString = searchClient.search(criteria);
      return convertJson(resultInString)
  }
}

public DocSearchResponse<T> convertJson(String result){
     return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});
  }
}

in Project B:在项目 B 中:

public class Account{
 private String name;
 //come with other attributes
}

and i use ServiceA from library to make query and as well convert data我使用库中的 ServiceA 进行查询并转换数据

public class ServiceAImpl extends ServiceA<Account> {
    
}

and make use of that并利用它

public class MakingAccountService {
    @Autowired
    private ServiceA service;
    public void execute(Criteria criteria){
      
        DocSearchResponse<Account> result = service.query(criteria);
        Account acc = result.getData(); //  java.util.LinkedHashMap cannot be cast to com.testing.models.Account
    }
}

it happen because from classloader of LibraryA, jackson can not load Account class, then just override method convertJson in Project B to let jackson do its job这是因为从 LibraryA 的类加载器中,jackson 无法加载 Account 类,然后只需覆盖项目 B 中的方法convertJson即可让 jackson 完成其工作

public class ServiceAImpl extends ServiceA<Account> {
        @Override
        public DocSearchResponse<T> convertJson(String result){
         return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});
      }
    }
 }

This is something i used in my project, Json object was returned, i converted it to a List of POJO, List and then accessed the element.这是我在我的项目中使用的东西,返回了 Json 对象,我将其转换为 POJO 列表,然后访问该元素。 I took the input of Json object from another microservice.我从另一个微服务中获取了 Json 对象的输入。

Main thing is:- JsonNode stocks = restTemplate.getForObject("http://localhost:2000/stocks/qty", JsonNode.class);主要是:- JsonNode stock = restTemplate.getForObject("http://localhost:2000/stocks/qty", JsonNode.class); List<Stock_id_qty> stockList = mapper.convertValue(stocks, new TypeReference<List<Stock_id_qty>>() {}); List<Stock_id_qty> stockList = mapper.convertValue(stocks, new TypeReference<List<Stock_id_qty>>() {});

@GetMapping("/")
    public List<Stock_id_qty> checkQty() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode stocks = restTemplate.getForObject("http://localhost:2000/stocks/qty", JsonNode.class);
        List<Stock_id_qty> stockList = mapper.convertValue(stocks, new TypeReference<List<Stock_id_qty>>() {});
        List<Stock_id_qty> result = new ArrayList<>();
        for(Stock_id_qty s : stockList){
            if(s.getStockQty() < 10)
            {
                result.add(s);
            }
        }
        return result;
    }
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.convertValue(map.get(key), new TypeReference<Account>() {});
public class ObjectHelper { private static ObjectMapper objectMapper = new ObjectMapper(); public static ObjectMapper getObjectMapper() { objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false); return objectMapper; } }

Use利用

FetchResponse fetchResponse = ObjectHelper.getObjectMapper().convertValue( data, new TypeReference<FetchResponse>() {});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 java.lang.ClassCastException:无法强制转换java.util.LinkedHashMap - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast java.lang.ClassCastException:无法将java.util.LinkedHashMap强制转换为com。****。db。***** - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.****.db.***** java.lang.ClassCastException:无法将java.util.LinkedHashMap强制转换为com.example.backendtest.Project - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.example.backendtest.Project java.lang.ClassCastException:com.google.gson.internal.LinkedTreeMap无法转换为java.util.LinkedHashMap - java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to java.util.LinkedHashMap java.lang.ClassCastException:java.util.LinkedHashMap 无法转换为 com..dto.PersonDto - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com..dto.PersonDto Java Spring rest java.lang.ClassCastException:java.util.LinkedHashMap 不能转换为 Cuestionario - Java Spring rest java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to Cuestionario java.lang.ClassCastException:java.util.LinkedHashMap 无法转换为 java.time.LocalDateTime - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.time.LocalDateTime 请求处理失败; 嵌套异常是 java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to MyClass - Request processing failed; nested exception is java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to MyClass 线程“主”java.lang.ClassCastException 中的异常:java.util.LinkedHashMap 无法转换为自定义 Object - Exception in thread “main” java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to Custom Object spring-data-redis @Cacheable java.lang.ClassCastException: java.util.LinkedHashMap 无法转换为 MyObject - Spring-data-redis @Cacheable java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to MyObject
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM