Cocos2d-x 3.0 JSON Usage cocos2d-x XML parsing

Source: Internet
Author: User
Tags gettext

Cocos2d-x 3.0 joins the Rapidjson library for JSON parsing. Located under External/json.

Rapidjson Project Address: http://code.google.com/p/rapidjson/wiki:http://code.google.com/p/rapidjson/wiki/UserGuide

The following is an example code explaining the use of Rapidjson.

Parsing JSON strings using Rapidjson
  1. Introducing Header Files

    12 #include "json/rapidjson.h"#include "json/document.h"
  2. JSON parsing

    12345678910111213 std::string str = "{\"hello\" : \"word\"}";CCLOG("%s\n", str.c_str());rapidjson::Document d;d.Parse<0>(str.c_str());if (d.HasParseError())  //打印解析错误{    CCLOG("GetParseError %s\n",d.GetParseError());} if (d.IsObject() && d.HasMember("hello")) {    CCLOG("%s\n", d["hello"].GetString());//打印获取hello的值}
  3. Print results

    123 cocos2d: {"hello": "word"}cocos2d: word

Note: Only the standard JSON format is supported, and some non-standard JSON formats are not supported.

Some common parsing methods need to be packaged themselves. Be careful to determine if the resolution node exists.

Using Rapidjson to generate JSON strings
  1. Introducing Header Files

    1234 #include "json/document.h"#include "json/writer.h"#include "json/stringbuffer.h"usingnamespacerapidjson;
  2. Generating a JSON string

    12345678910111213141516171819 rapidjson::Document document;document.SetObject();rapidjson::Document::AllocatorType& allocator = document.GetAllocator();rapidjson::Value array(rapidjson::kArrayType);rapidjson::Value object(rapidjson::kObjectType);object.AddMember("int", 1, allocator);object.AddMember("double", 1.0, allocator);object.AddMember("bool", true, allocator);object.AddMember("hello", "你好", allocator);array.PushBack(object, allocator);document.AddMember("json", "json string", allocator);document.AddMember("array", array, allocator);StringBuffer buffer;rapidjson::Writer<StringBuffer> writer(buffer);document.Accept(writer);CCLOG("%s",buffer.GetString());
  3. Print results

    1 cocos2d: {"json":"json string","array":[{"int":1,"double":1,"bool":true

    Cocos2d-x has added tinyxml2 parsing for XML. Version 3.0 is located external/tinyxml2 under. The 2.x version is located cocos2dx/support/tinyxml2 under.

    TINYXML2 GitHub Address: HTTPS://GITHUB.COM/LEETHOMASON/TINYXML2

    Help document Address: http://grinninglizard.com/tinyxml2docs/index.html

    Generating an XML document
    1. Introducing Header Files

      12 #include "tinyxml2/tinyxml2.h"usingnamespacetinyxml2;
    2. XML document Generation

      123456789101112131415161718192021222324252627282930313233343536373839404142 voidHelloWorld::makeXML(const char *fileName){std::string filePath = FileUtils::getInstance()->getWritablePath() + fileName;XMLDocument *pDoc = new XMLDocument();//xml 声明(参数可选)XMLDeclaration *pDel = pDoc->NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\"");pDoc->LinkEndChild(pDel);//添加plist节点XMLElement *plistElement = pDoc->NewElement("plist");plistElement->SetAttribute("version", "1.0");pDoc->LinkEndChild(plistElement);XMLComment *commentElement = pDoc->NewComment("this is xml comment");plistElement->LinkEndChild(commentElement);//添加dic节点XMLElement *dicElement = pDoc->NewElement("dic");plistElement->LinkEndChild(dicElement);//添加key节点XMLElement *keyElement = pDoc->NewElement("key");keyElement->LinkEndChild(pDoc->NewText("Text"));dicElement->LinkEndChild(keyElement);XMLElement *arrayElement = pDoc->NewElement("array");dicElement->LinkEndChild(arrayElement);for (int i = 0; i<3; i++) {    XMLElement *elm = pDoc->NewElement("name");    elm->LinkEndChild(pDoc->NewText("Cocos2d-x"));    arrayElement->LinkEndChild(elm);}pDoc->SaveFile(filePath.c_str());pDoc->Print();delete pDoc;}
    3. Print results

      123456789101112 <?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><!--this is xml comment--><dic>    <key>Text</key>    <array>        <name>Cocos2d-x</name>        <name>Cocos2d-x</name>        <name>Cocos2d-x</name>    </array></dic></plist>

    The above code uses TinyXML to simply generate an XML document.

    Parsing xml

    Here we will parse the XML document created above

    1. Introducing Header Files

      12 #include "tinyxml2/tinyxml2.h"usingnamespacetinyxml2;
    2. XML parsing

      1234567891011121314151617181920212223242526272829303132333435 void HelloWorld::parseXML(const char *fileName){std::string filePath = FileUtils::getInstance()->getWritablePath() + fileName;XMLDocument *pDoc = new XMLDocument();XMLError errorId = pDoc->LoadFile(filePath.c_str());if (errorId != 0) {    //xml格式错误    return;} XMLElement *rootEle = pDoc->RootElement();//获取第一个节点属性const XMLAttribute *attribute = rootEle->FirstAttribute();//打印节点属性名和值log("attribute_name = %s,attribute_value = %s", attribute->Name(), attribute->Value());XMLElement *dicEle = rootEle->FirstChildElement("dic");XMLElement *keyEle = dicEle->FirstChildElement("key");if (keyEle) {    log("keyEle Text= %s", keyEle->GetText());}XMLElement *arrayEle = keyEle->NextSiblingElement();XMLElement *childEle = arrayEle->FirstChildElement();while ( childEle ) {    log("childEle Text= %s", childEle->GetText());    childEle = childEle->NextSiblingElement();}delete pDoc;}

      In the process of node parsing, pay attention to the empty processing of the obtained node.

    3. Parsing results Printing

      12345 cocos2d: attribute_name = version,attribute_value = 1.0cocos2d: keyEle Text= Textcocos2d: childEle Text= Cocos2d-xcocos2d: childEle Text= Cocos2d-xcocos2d: childEle Text= Cocos2d-x
    Summary

    The simple example above demonstrates how to use TinyXML for XML document generation and parsing. For more detailed help, please refer to the TinyXML Help documentation http://grinninglizard.com/tinyxml2docs/index.html

Cocos2d-x 3.0 JSON Usage cocos2d-x XML parsing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.