Because the project needs to be parsed in json format, I have never been touched by it at the beginning, so I am worried about it, but now I can understand it. I will share with you that my cocos2dx version is 2.2.1.
Add the header file as follows:
#include "HelloWorldScene.h"#include "json_lib.h"using namespace std;USING_NS_CC;
Two functions are written here.
// Here is the Value for obtaining jsonvalue CSJson: Value HelloWorld: getJsonFromFile (const char * fileName) {CSJson: Reader reader; CSJson: Value jsValue; unsigned long ilength; // parse the file and pay it to the pBuffer string (I have never touched this sentence before, and it is a headache ....) char * pBuffer = (char *) CCFileUtils: sharedFileUtils ()-> getFileData (getFullPath (fileName ). c_str (), "r", & ilength); CCLog ("% s", pBuffer); // pay the pBuffer value to the jsValue value bool parseRet = reader. parse (pBuffer, jsValu E, false); CCAssert (parseRet, "Read GridData Error ~!!!!!!!!! "); Return jsValue ;}
Second Function
// Obtain the resource path std: string HelloWorld: getFullPath (const char * path) {CCLOG (cocos2d: CCFileUtils: sharedFileUtils ()-> fullPathForFilename (path ). c_str (); return cocos2d: CCFileUtils: sharedFileUtils ()-> fullPathForFilename (path );}
Finally, write in init
CSJson: Reader read; CSJson: Value myjson = getJsonFromFile ("jsontest. json"); // use the above function to generate a json file. String name; int I = 0; // here is the value for traversing the entire jsonvalue (CSJson: ValueIterator a = myjson. begin ();! = Myjson. end (); ++ a) {CSJson: Value value = (CSJson: Value) * a; name = value ["name"]. asString (); CCLOG ("myjson: % s", name. c_str (); CCLOG ("leftBottom: % s", value ["leftBottom"]. asCString (); CCLOG ("leftTop: % s", value ["leftTop"]. asCString (); CCLOG ("rightBottom: % s", value ["rightBottom"]. asCString (); CCLOG ("rightTop: % s", value ["rightTop"]. asCString (); CCLOG ("position: % s", value ["position"]. asCString (); // you can select the above character as my field name = myjson [I] ["name"]. asString (); CCLOG ("myjson: % s", name. c_str (); CCLOG ("leftBottom: % s", myjson [I] ["leftBottom"]. asCString (); CCLOG ("leftTop: % s", myjson [I] ["leftTop"]. asCString (); CCLOG ("rightBottom: % s", myjson [I] ["rightBottom"]. asCString (); CCLOG ("rightTop: % s", myjson [I] ["rightTop"]. asCString (); CCLOG ("position: % s", myjson [I] ["position"]. asCString (); I ++ ;}
Then you can print it out. I wish you success !!!