5

I am creating a application in vc++ to call webservice in json format,without using json library to serialize /deserialize the string .I am sending the json string by manually constructing it.Can anybody help me how I can deserialize the jason string without using any library in c++

Response

{ 
    "Result": "1",
    "gs":"0",
    "ga":"0",
    "la":"0",
    "lb":"0",
    "lc":"0",
    "ld":"0",
    "ex":"0",
    "gd":"0"        
}
4

2 回答 2

2

这只是使用 stl 解析响应字符串的粗略实现,但您可以将其用作进一步处理的起点。如果您可以使用任何正则表达式(例如boost::regex),则此解析可以更简单,但是您也可以使用特定的 json 解析器,所以忘记这个;)

#include <iostream>
#include <sstream>
#include <string>

const char* response = "\
\
{\
    \"Result\": \"1\",\
    \"gs\":\"0\",\
    \"ga\":\"0\",\
    \"la\":\"0\",\
    \"lb\":\"0\",\
    \"lc\":\"0\",\
    \"ld\":\"0\",\
    \"ex\":\"0\",\
    \"gd\":\"0\"\
}";

int main(int argc, char* argv[])
{
    std::stringstream ss(response); //simulating an response stream
    const unsigned int BUFFERSIZE = 256;

    //temporary buffer
    char buffer[BUFFERSIZE];
    memset(buffer, 0, BUFFERSIZE * sizeof(char));

    //returnValue.first holds the variables name
    //returnValue.second holds the variables value
    std::pair<std::string, std::string> returnValue;

    //read until the opening bracket appears
    while(ss.peek() != '{')         
    {
        //ignore the { sign and go to next position
        ss.ignore();
    }

    //get response values until the closing bracket appears
    while(ss.peek() != '}')
    {
        //read until a opening variable quote sign appears
        ss.get(buffer, BUFFERSIZE, '\"'); 
        //and ignore it (go to next position in stream)
        ss.ignore();

        //read variable token excluding the closing variable quote sign
        ss.get(buffer, BUFFERSIZE, '\"');
        //and ignore it (go to next position in stream)
        ss.ignore();
        //store the variable name
        returnValue.first = buffer;

        //read until opening value quote appears(skips the : sign)
        ss.get(buffer, BUFFERSIZE, '\"');
        //and ignore it (go to next position in stream)
        ss.ignore();

        //read value token excluding the closing value quote sign
        ss.get(buffer, BUFFERSIZE, '\"');
        //and ignore it (go to next position in stream)
        ss.ignore();
        //store the variable name
        returnValue.second = buffer;

        //do something with those extracted values
        std::cout << "Read " << returnValue.first<< " = " << returnValue.second<< std::endl;
    }
}
于 2012-04-24T11:38:05.697 回答
1

这是一个小例子,说明如何将boost::spirit::qi用于此类目的。

请注意,Boost确实是第三方库!

假设您收到一个 JSON 文件并将其保存在json-example.txt中,内容如下:

{
    "结果":"1",
    "gs":"0",
    “嘎”:“0”,
    “拉”:“0”,
    “磅”:“0”,
    "lc":"0",
    “ld”:“0”,
    “前”:“0”,
    “gd”:“0”
}

现在,假设您想以key:file方式接收所有项目。你可以这样做:

#include <vector>
#include <string>
#include <fstream>
#include <map>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/adapted/std_pair.hpp>

namespace qi = boost::spirit::qi;

template<typename Iterator>
struct jsonparser : qi::grammar<Iterator, std::map<std::string, int>()>
{
    jsonparser() : jsonparser::base_type(query, "JSON-parser")
    {
        using qi::char_;
        using qi::int_;
        using qi::blank;
        using qi::eol;
        using qi::omit;

        query = omit[-(char_('{') >> eol)] >> pair % (eol | (',' >> eol)) >> '}';

        pair  = key >> -(':' >> value);

        key   = omit[*blank] >> '"' >> char_("a-zA-Z_") >> *char_("a-zA-Z_0-9") >> '"';

        value = '"' >> int_ >> '"';

    };

    qi::rule<Iterator, std::map<std::string, int>()> query;
    qi::rule<Iterator, std::pair<std::string, int>()> pair;
    qi::rule<Iterator, std::string()> key;
    qi::rule<Iterator, int()> value;

};

void main(int argc, char** argv)
{
    // Copy json-example.txt right in the std::string
    std::string jsonstr
    (
        (
            std::istreambuf_iterator<char>
            (
                *(std::auto_ptr<std::ifstream>(new std::ifstream("json-example.txt"))).get()
            )
        ),
        std::istreambuf_iterator<char>()
    );

    typedef std::string::iterator StrIterator;

    StrIterator iter_beg = jsonstr.begin();
    StrIterator iter_end = jsonstr.end();

    jsonparser<StrIterator> grammar;

    std::map<std::string,int> output;

    // Parse the given json file
    qi::parse(iter_beg, iter_end, grammatic, output);

    // Output the result
    std::for_each(output.begin(), output.end(), 
            [](const std::pair<std::string, int> &item) -> void 
            { 
                    std::cout << item.first << ":" << item.second << std::endl; 
            });
}

输出:

结果:1
gs:0
加:0
拉:0
磅:0
液晶:0
ld:0
例如:0
gd:0
于 2012-04-26T06:44:46.837 回答