web3j调用智能合约,解析数组对象类型

883 阅读1分钟

image.png

[{Uint256,Address,Uint256},{Uint256,Address,Uint256},{Uint256,Address,Uint256}]

web3j处理这种数组对象时,无法直接解析对象,需要按照基本类型单独处理

1、在合约上按照以下图片,按照getUser1()方法,进行处理返回数据。

image.png

2、生成智能合约包装器

public RemoteFunctionCall<Tuple3<List<BigInteger>, List<String>, List<BigInteger>>> getShop2() {
    final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_GETSHOP2,
            Arrays.<Type>asList(), 
            Arrays.<TypeReference<?>>asList(new TypeReference<DynamicArray<Uint256>>() {},
                    new TypeReference<DynamicArray<Address>>() {},
                    new TypeReference<DynamicArray<Uint256>>() {}));
    return new RemoteFunctionCall<Tuple3<List<BigInteger>, List<String>, List<BigInteger>>>(function,
            new Callable<Tuple3<List<BigInteger>, List<String>, List<BigInteger>>>() {
                @Override
                public Tuple3<List<BigInteger>, List<String>, List<BigInteger>> call() throws Exception {
                    List<Type> results = executeCallMultipleValueReturn(function);
                    return new Tuple3<List<BigInteger>, List<String>, List<BigInteger>>(
                            convertToNative((List<Uint256>) results.get(0).getValue()), 
                            convertToNative((List<Address>) results.get(1).getValue()), 
                            convertToNative((List<Uint256>) results.get(2).getValue()));
                }
            });
}

3、拿到数据进行重新组装

//获取到的数据
val tuple3: Tuple3<List<BigInteger>, List<String>, List<BigInteger>> =
    market_sol_MarketShoes.shop2.sendAsync().join()
val list: MutableList<SalesForReturn> = mutableListOf()
for (i in tuple3.component1().indices) {
    val salesForReturn = SalesForReturn()
    salesForReturn.tokenId = tuple3.component1()[i]
    salesForReturn.seller = tuple3.component2()[i]
    salesForReturn.price = tuple3.component3()[i]
    list.add(salesForReturn)
}
LogUtils.d(GsonUtils.toJson(list))

参考:www.youtube.com/watch?v=QGj…