C ++ JSON Parser

时间:2016-02-23 01:34:01

标签: c++ json c++11

对于我的课程,我正在编写一个JSON解析器来浏览音乐艺术家的JSON数组。 它的外观如下:

 [ 
    { "artist_name" : "Beatle, The", 
     "real_name" : "Unknown", 
     "artist_id" : 82730,
      "profile": "A phenomenally successful..." 
     } 
   ]

我们不允许使用任何形式的JSON解析器库。自星期五以来,我一直坚持以下几个功能,我不确定是什么问题。

void Artist::artistParsefromJSONstream(fstream &stream)
{
    readJSONarray(stream);
}

void Artist::readJSONarray(fstream &stream)
{
    char c;

    if (!(stream >> c) || c != '[')
    {
        cerr << "readJSONarray exit";
        exit(2);
    } // exit
    do
    {
        readJSONDataObject(stream);
        stream >> c;
    } while (c != ']');
}

void Artist::readJSONDataObject(fstream &stream)
{
    char c;

    if (!(stream >> c || c != '{'))
    {
      cerr << "JSON Data Object exit";
      exit(3);
    }
    do
    {
        readJSONDataItem(stream);
        stream >> c;
    } while (c != '}');

}

void Artist::readJSONDataItem(fstream &stream)
{
    char c;
    string key;

    if (!(stream >> c || c != '"'))
    {
        cerr << "Data item exit";
        exit(4);
    }
    key += c;

    do
    {
        stream.get(c);
        key += c;
    } while(c != '"');


    if (!(stream >> c) || c != ':')
    {
        cerr << "colon not found";
        exit(5);
    }
    stream >> c;

    if (isdigit(c))
    {
        stream.unget();
        int number;
        stream >> number;
    }
    else
    {
        if (key == "artist_name")
        {
            char x;
            string s;

            stream >> x;
            s += x;
            while(x != '"')
            {
                stream.get(x);
                s+=x;
            }

            _name = s;
            cout << _name << " \n";
        }
        if (key == "real_name")
        {
            char x;
            string s;

            stream >> x;
            while(x != '"')
            {
                s += x;
                stream.get(x);
            }

            _realName = s;
            cout << _realName << " \n";
        }

        if (key == "profile")
        {
            char x;
            string s;

            stream >> x;
            while(x != '"')
            {
                s+= x;
                stream.get(x);
            }

            _profile = s;
            cout << _profile << " \n";
        }

        if (key == "num_images")
        {
            char x;
            string s;

            stream >> x;
            while( x != '"')
            {
                _numImages += x;
                stream.get(x);
            }

            cout << _numImages << " \n";
            _numImages = "";
        }
    }
}

期望的输出:

Beatles, The  
Unknown  
A phenomenally successful ...  

然后移动到数组中的下一个对象。

实际输出:

eatles, The"  
colon not found  

有关如何解决此问题的任何建议吗?

0 个答案:

没有答案