本文介紹了使用Chainlink大型響應示例從任何API獲取字符串的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我只需要從這個json中獲取一個字符串,例如:https://filesamples.com/samples/code/json/sample1.json
我采用了Chainlink示例,只更改了URL和路徑。該示例運行良好,但如果使用不同的json o jobid,則無法運行。
鏈接到鏈接示例:https://docs.chain.link/docs/large-responses/
有什么辦法可以解決這個問題嗎?
使用的代碼:
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";
/**
* @notice DO NOT USE THIS CODE IN PRODUCTION. This is an example contract.
*/
contract GenericLargeResponse is ChainlinkClient {
using Chainlink for Chainlink.Request;
// variable bytes returned in a signle oracle response
bytes public data;
string public dataS;
/**
* @notice Initialize the link token and target oracle
* @dev The oracle address must be an Operator contract for multiword response
*
*
* Kovan Testnet details:
* Link Token: 0xa36085F69e2889c224210F603D836748e7dC0088
* Oracle: 0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8 (Chainlink DevRel)
*
*/
constructor(
) {
setChainlinkToken(0xa36085F69e2889c224210F603D836748e7dC0088);
setChainlinkOracle(0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8);
}
/**
* @notice Request variable bytes from the oracle
*/
function requestBytes(
)
public
{
bytes32 specId = "7a97ff8493ec406d90621b2531f9251a";
uint256 payment = 100000000000000000;
Chainlink.Request memory req = buildChainlinkRequest(specId, address(this), this.fulfillBytes.selector);
req.add("get","https://filesamples.com/samples/code/json/sample1.json");
req.add("path", "fruit");
requestOracleData(req, payment);
}
event RequestFulfilled(
bytes32 indexed requestId,
bytes indexed data
);
/**
* @notice Fulfillment function for variable bytes
* @dev This is called by the oracle. recordChainlinkFulfillment must be used.
*/
function fulfillBytes(
bytes32 requestId,
bytes memory bytesData
)
public
recordChainlinkFulfillment(requestId)
{
emit RequestFulfilled(requestId, bytesData);
data = bytesData;
dataS = string(data);
}
}
推薦答案
該接口返回:
{
"fruit": "Apple",
"size": "Large",
"color": "Red"
}
fruit
的值為Apple
。您需要讓API返回Apple
的字節版本。
您會注意到該示例返回如下所示的JSON:
{
"image": "0x68747470733a2f2f697066732e696f2f697066732f516d5358416257356b716e3259777435444c336857354d736a654b4a4839724c654c6b51733362527579547871313f66696c656e616d653d73756e2d636861696e6c696e6b2e676966"
}
哪個是圖像URL的十六進制版本。
這篇關于使用Chainlink大型響應示例從任何API獲取字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,