How can we parse data that have null in the json.
In the example, below the first Json (json1) did not have any null as its values gets the desired result. But in the second call here the value of has a null hence will crash the application.
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
#include <string>
using namespace rapidjson;
bool ParseStarName( std::string json, std::string& strStarName)
{
Document d;
d.Parse(json.c_str());
if( d.IsObject() )
{
auto itStars = d.FindMember("stars");
if( itStars != d.MemberEnd() )
{
auto &star = itStars->value;
auto itName = star.FindMember("name");
if( itName != d.MemberEnd() )
{
strStarName = itName->value.GetString();
return true;
}
}
}
return false;
}
int _tmain(int argc, _TCHAR* argv[])
{
const char* json1 = "{\"stars\":{ \"name\": \"1\" }}";
const char* json2 = "{\"stars\":null}";
std::string strStarName;
//No error
ParseStarName( json1, strStarName);
//Error
ParseStarName( json2, strStarName);
return 0;
}
Is there a better call or a better way to handle this issue. In real case we get such jsons with null value from a third party api.
Aucun commentaire:
Enregistrer un commentaire