如何在不使用任何第三方库的情况下在 C++ 中反序列化 json 字符串

sac*_*hin 5 c++ json visual-c++

我正在 vc++ 中创建一个应用程序以 json 格式调用 webservice,而不使用 json 库来序列化/反序列化字符串。我正在通过手动构建它来发送 json 字符串。有人可以帮助我如何反序列化 jason 字符串而不使用任何C++ 中的库

回复

{ 
    "Result": "1",
    "gs":"0",
    "ga":"0",
    "la":"0",
    "lb":"0",
    "lc":"0",
    "ld":"0",
    "ex":"0",
    "gd":"0"        
}
Run Code Online (Sandbox Code Playgroud)

Aqu*_*pax 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;
    }
}
Run Code Online (Sandbox Code Playgroud)