简介:上一节,我们介绍智能合约开发中常用的Lib工具库的第一部分。由于内容较长,工具库我们将分两部分介绍,本文将介绍Lib工具库的第二部分:LibJson 、LibStack和LibLog。
LibJson
LibJson主要封装了对JSON格式的字符串一些操作;
支持直接调用、using for *;调用
注意:正如在Lib工具库说明中提到的,LibJson 库的使用稍微有点特殊:
不管是直接调用,还是using for *;方式调用,在合约方法中,如果要使用一次、或者多次LibJson库中的方法,则在第一次使用LibJsos库方法前,需要对被操作的json字符串进行如下操作:
//字符串入栈
LibJson.push(_json);
在最后一个LibJsos库方法之后,要进行如下操作
//出栈
LibJson.pop();
示例:
pragma solidity ^0.4.2;
import "./utillib/LibJson.sol";
contract TestManager {
using LibJson for *;
string[] public _arr;
function test() constant returns(bool _ret) {
string memory _json = "{\"errno\":27,\"hash\":\"0xf16a2a734ccf0456807e166ad310ec7767f71e8d4003154b73596741683c6433\",\"nodeId\":\"JZNCGP\",\"type\":1}";
// step01: 字符串入栈
LibJson.push(_json);
// step02: 操作字符串,判断自否为一个合法的json格式
bool isJson = _json.isJson();
//或者直接调用
//bool isJson = LibJson.isJson(_json);
_json.jsonRead("nodeId"); // "JZNCGP"
// step03: 出栈
LibJson.pop();
}
}
- LibJson.push() 与 LibJson.pop() 一定是成对出现的;
- 当对字符串的操作结束后务必调用pop将栈中的元素移除掉;
JSON格式判断
描述:判断指定串是否为标准的JSON格式
结构定义
function isJson(string _json) internal constant returns(bool _ret);
示例
string memory _json = "{\"errno\":27,\"hash\":\"0xf16a2a734ccf0456807e166ad310ec7767f71e8d4003154b73596741683c6433\",\"nodeId\":\"JZNCGP\",\"type\":1}";
bool _ret= _json.isJson(); // _ret = true
读取JSON中key的值