programing

java.displaces를 클릭합니다.ClassCastException: java.util.LinkedHashMap을 com.testing.models로 캐스트할 수 없습니다.계좌

randomtip 2022. 10. 2. 11:05
반응형

java.displaces를 클릭합니다.ClassCastException: java.util.LinkedHashMap을 com.testing.models로 캐스트할 수 없습니다.계좌

다음과 같은 에러가 발생합니다.

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

아래 코드와 함께

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

할 수 없는 이유라도 있나요?get(0)?

이 문제는 잭슨에게서 온 거야.어떤 클래스에 대한 충분한 정보가 없을 경우,LinkedHashMap.

잭슨에게 그 원소의 종류를 알려주지 않으셨기 때문에ArrayList디시리얼라이즈 할 필요가 있는지 아닌지는 알 수 없습니다.ArrayListAccounts. 따라서 디폴트로 돌아갑니다.

대신, 아마도as(JsonNode.class), 그리고 나서ObjectMapper휴식시간이 허락하는 것보다 더 풍성한 방법으로.다음과 같은 경우:

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

다음을 시도해 보십시오.

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

또는 다음과 같이 입력합니다.

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

자세한 내용은 LinkedHashMap 변환을 참조하십시오.

LinkedHashMap 오브젝트 수집에 대한 JSON 어레이 문제를 완화하는 방법은CollectionType가 아니라TypeReference제가 한 은 다음과 같습니다.

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;
}

사용방법TypeReferenceLinked Hash Maps의 Array List가 아직 표시되어 있습니다.즉, 동작하지 않습니다.

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;
}

비슷한 예외(다만 다른 문제)가 있었습니다.java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.bson.Document다행스럽게도 이 문제는 쉽게 해결되었습니다.

대신

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

두 번째 줄에 오류가 표시됩니다.

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

공통 구문 분석 두 가지 방법으로 문제 해결

  1. Whith 유형은 개체입니다.
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. 유형이 컬렉션 랩 개체입니다.
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;
}

이것은 제 프로젝트에서 사용한 것입니다.Json 오브젝트가 반환되어 POJO, List로 변환되어 엘리먼트에 액세스했습니다.다른 마이크로 서비스에서 Json 오브젝트를 입력했습니다.

주요 내용은 다음과 같습니다.- JsonNode stocks = restTemplate.getForObject("http://localhost:2000/stocks/qty", JsonNode.class) 목록 <Stock_id_qty> stockList = mapper.convertValue (stocks, new TypeReference <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;
    }

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 );   
}

다음은 콜입니다.

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

Jackson을 사용하여 문자열에서 구체적인 클래스로 매핑하는 경우, 특히 일반 유형을 사용하는 경우.이 문제는 클래스 로더가 다르기 때문에 발생할 수 있습니다.한번은 아래와 같은 장면에서 만난 적이 있습니다.

프로젝트 B는 라이브러리 A에 의존합니다.

라이브러리 A:

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

외부 소스에서 데이터를 조회하고 잭슨을 사용하여 구체적인 클래스로 변환하는 서비스를 제공합니다.

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>>() {});
  }
}

프로젝트 B:

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

또한 라이브러리의 ServiceA를 사용하여 쿼리를 작성하고 데이터를 변환합니다.

public class ServiceAImpl extends ServiceA<Account> {
    
}

그것을 활용하다

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

A의 클래스를 수하며 메서드 Library를 .A' 클래스 로더 계정입니다.convertJson 이 그 일을할 수 있도록

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

사용하다

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

또는

List<Map<String, Object>> responseObj = (List<Map<String, Object>>) response.get("content");

List<LkAuthUserDetail> responseData = ObjectHelper.getObjectMapper().convertValue(responseObj,
                    new TypeReference<List<LkAuthUserDetail>>() {});

언급URL : https://stackoverflow.com/questions/28821715/java-lang-classcastexception-java-util-linkedhashmap-cannot-be-cast-to-com-test

반응형