ClassCastException:com.fasterxml.jackson.databind.node.MissingNode无法强制转换为com.fasterxml.jackson.databind.node.Arraynode

时间:2017-03-28 14:00:01

标签: spring-integration classcastexception

我有一个将数据从instagram映射到我的系统的读者。执行Junit测试时,我遇到了ClassCastException。我的测试类有以下代码:

public class InstagramToJsonMapperTest extends AbstractMapperTest {

private InstagramMapper instagramMapper;
private boolean printResult = true;

@Before
    public void setup() {
        super.setup();
        instagramMapper = new InstagramMapper(128);
    }

    private void compareJson(String unmapped, String mapped) throws Exception {
        JsonNode unmappedJson = loadJson(unmapped);
        JsonNode mappedJson = loadJson(mapped);
        Message<JsonNode> msg = MessageBuilder.withPayload(unmappedJson).build();
        Message<JsonNode> resultMsg = instagramMapper.map(msg);
        JsonNode result = resultMsg.getPayload();
        if(printResult) {
            System.out.println("processed: " + result);
            System.out.println("expected: " + mappedJson.toString());
        }
        Assert.assertTrue(JacksonUtils.equals(result, mappedJson));
    }

    @Test
    public void testPhoto() throws Exception {
        compareJson("/mapping/test.json", "/mapping/test_mapped.json");
    }

}

错误是由于我的映射器中的这一行:

String[] branches = JacksonUtils.toArray((ArrayNode) extractor.extract("contentBranch"));
        if(branches.length == 1) {
            abc.put("contentBranch", branches[0]);
        } else {
            abc.set("contentBranch", JacksonUtils.arrayToArrayNode(branches));
        }

我的问题是,我不知道该改变什么。我应该更改我的映射器代码或我的测试文件中的代码。错误是:

ClassCastException: com.fasterxml.jackson.databind.node.MissingNode cannot be 
    cast to com.fasterxml.jackson.databind.node.Arraynode

1 个答案:

答案 0 :(得分:1)

您需要使用JsonNode node = extractor.extract("contentBranch"),然后测试返回的实际节点类型。

在您的情况下,您获得的MissingNode无法投放到ArrayNode

if (node instanceof ArrayNode) {...}
else {...}