How to read this string into jsoncpp 's Json::Value - jsoncpp

I have such a json string :
{"status":0,"bridge_id":"bridge.1","b_party":"85267191234","ref_id":"20180104151432001_0","function":{"operator_profile":{"operator":"aaa.bbb"},"subscriber_profile":{"is_allowed":true,"type":8},"name":"ServiceAuthen.Ack"},"node_id":"aaa.bbb.collector.1"}
how can I read it into jsoncpp lib 's Json::Value object ?
I found such code by searching stackoverflow :
std::string strJson = "{\"mykey\" : \"myvalue\"}"; // need escape the quotes
Json::Value root;
Json::Reader reader;
bool parsingSuccessful = reader.parse( strJson.c_str(), root ); //parse process
if ( !parsingSuccessful )
{
std::cout << "Failed to parse"
<< reader.getFormattedErrorMessages();
return 0;
}
std::cout << root.get("mykey", "A Default Value if not exists" ).asString() << std::endl;
return 0;
but how to convert my string to this form ?
{\"mykey\" : \"myvalue\"}
thank you for any help .

You don't.
The slash characters are escape characters used to represent a " in C++ source code (without them the " would mean "This is the end of this C++ string literal").
The JSON (which isn't C++ source code) should not have the escape characters in it.

Related

Qt keyboard enum to QString

I have a piece of code like this :
if(keyEvent->key()==Qt::Key_S && keyEvent->modifiers()==Qt::AltModifier)
{
// my code
}
I want to replace Qt::Key_S and Qt::AltModifier by two strings "KEY_S" and "ALT" which I intend to read from a file. I have no idea how to do it. I have tried QKeySequence, which is not working. Can anyone help?
If you get the Qt::Key value in a QKeyEvent then just use QKeyEvent::text() :
QString stringKey = event->text();
But as it is stated in the doc :
Return values when modifier keys such as Shift, Control, Alt, and Meta
are pressed differ among platforms and could return an empty string.
So you might want to handle them one by one, just by giving them the string you want to associate :
if (event->key() == Qt::Key_Alt)
QString stringKey = "ALT";
You can use Qt meta object system to get real names of enum keys as strings at runtime:
void keyPressEvent(QKeyEvent* e) {
int enum_index = qt_getQtMetaObject()->indexOfEnumerator("Key");
const char* string =
qt_getQtMetaObject()->enumerator(enum_index).valueToKey(e->key());
qDebug() << string;
}
Note that valueToKey may return null pointer if there is no corresponding key.

DDE connection failing for unknown reasons

I'm trying to create and implement a DDE dll with Qt but as for now I'm being unable to properly connect to a service which I know to be working after testing it with Excel.
The dll connection function is as following:
UINT respTemp;
respTemp = DdeInitializeA(&pidInst, NULL, APPCLASS_STANDARD | APPCMD_CLIENTONLY, 0L);
//handle error messages here
//...
//![]
hszService = DdeCreateStringHandleA(pidInst, (LPCSTR)service.utf16(), CP_WINANSI); //service.toLatin1().toStdString().c_str()
hszTopic = DdeCreateStringHandleA(pidInst, (LPCSTR)topic.utf16(), CP_WINANSI); //topic.toLatin1().toStdString().c_str()
hConv = DdeConnect(pidInst, hszService, hszTopic, NULL);
DdeFreeStringHandle(pidInst, hszService);
DdeFreeStringHandle(pidInst, hszTopic);
if (!hConv)
{
UINT ddeLastError = DdeGetLastError(pidInst);
switch (ddeLastError)
{
case DMLERR_DLL_NOT_INITIALIZED: return DDEConn_DLLNotInitialized;
case DMLERR_INVALIDPARAMETER: return DDEConn_InvalidParameter;
case DMLERR_NO_CONV_ESTABLISHED: return DDEConn_NoConvEstablished;
default: return DDEConn_NoConnectionStablished;
}
}
connStatus = true;
return DDEConn_NoError;
The test function is as follows:
void MainWindow::on_start_clicked()
{
const QString application = "profitchart"; //=profitchart|COT!VALE5.ult
const QString topic = "COT";
const QString item = "VALE5.ult";
test = CommDDE::instance();
CommDDE::DDEConnectionErrorList resp = test->connect(application,topic);
if (resp == CommDDE::DDEConn_NoError)
{
qDebug() << "request RESULT: " << test->request(item);
}
else
qDebug() << "Can't connect to application" << resp;
}
Always when I try to connect I get error DMLERR_NO_CONV_ESTABLISHED after the call to DdeConnect. I couldn't find guidence on what to do when such error occurs. I don't know too much about the details of configuring such functions so I used the default configuration used by a working dll from which I got part of the raw material for this dll. Should I try a different configuration I'm not aware of? Remembering that the call is working on Excel.
It would seem I found the answer: the commented way of writting the service and topic names were the right ways of passing the parameters to DdeCreateStringHandleA and DdeCreateStringHandleA.

QLineEdit: automatically append backslash to directory name

I'm trying to automatically add a backslash to valid file paths in a QLineEdit, which is used to show the current path of a QFileSystemModel.
The code looks as follows:
fileSystem = new QFileSystemModel;
fileSystem->setRootPath(QObject::tr("C:\\"));
QCompleter* fileSystemCompleter = new QCompleter(fileSystem);
fileSystemCompleter->setCaseSensitivity(Qt::CaseInsensitive);
fileTree = new QDeselectableTreeView();
fileTree->setModel(fileSystem);
fileTree->setRootIndex(fileSystem->index(fileSystem->rootPath()));
connect(fileTree, &QTreeView::clicked, [&] (QModelIndex index)
{
QString toAppend("");
if (fileSystem->isDir(index))
{
toAppend = '/';
}
fileSystemPathEdit->setText(fileSystem->filePath(index)+toAppend);
});
// path line edit
fileSystemPathEdit = new QLineEdit(fileSystem->rootPath());
fileSystemPathEdit->setPlaceholderText("Path...");
fileSystemPathEdit->setCompleter(fileSystemCompleter);
connect(fileSystemPathEdit, &QLineEdit::editingFinished, [&]()
{
// jump to that location
qDebug() << fileSystemPathEdit->text();
QModelIndex index = fileSystem->index(fileSystemPathEdit->text());
qDebug() << index;
fileTree->setExpanded(index,true);
fileTree->setCurrentIndex(index);
// CLOSE IF EMPTY
if (fileSystemPathEdit->text().isEmpty())
{
fileTree->collapseAll();
fileSystemPathEdit->setText(fileSystem->rootPath());
}
// append slashes to dirs
else if (fileSystem->isDir(index) && index.isValid())
{
qDebug() << "it's a dir";
if (!fileSystemPathEdit->text().endsWith('/',Qt::CaseInsensitive))
{
qDebug() << "added slash";
fileSystemPathEdit->setText(fileSystemPathEdit->text().append('/'));
qDebug() << fileSystemPathEdit->text();
}
}
this->update();
});
I get the following output when running the code:
"C:/export/home"
QModelIndex(0,0,0x3adb840,QFileSystemModel(0x1d9b7c0) )
it's a dir
added slash
"C:/export/home/"
It works ok when I push the Enter key from within the lineEdit, but if the text is set by the QCompleter, I still get the same debug output showing that the text has been changed, but the slash doesn't appear in the lineEdit. Does the QCompleter somehow unset the text?
This is a hack, but adding this connection to the QCompleter gives the desired behavior. I think there is a race condition when using editingFinished() at the same time that the QCompleter is activated, so adding delay allows the slash to be appended without being overridden. On the down side, that function know gets called several times to many per change. I'd still be interested in a better solution.
connect(fileSystemCompleter, activatedOverloadPtr, [&](QModelIndex index)
{
QTimer* timer = new QTimer;
timer->setSingleShot(true);
timer->setInterval(10);
connect(timer, &QTimer::timeout, fileSystemPathEdit, &QLineEdit::editingFinished);
timer->start();
});

QVector: no match for 'operator+'

I am passing a QVector from one window to another, I want to append the value present in QVector from previous window to a QString in present window. I get the error when I perform the addition no match for 'operator+'.
Here is my code:
Window1.cpp
void SelectOS::processNextButton()
{
if(ui->win32->isChecked()){
QString path;
path = qApp->applicationDirPath()+"/WIN/32Bit";
so->osName.push_back(path);
SelectSoftware *ss = new SelectSoftware();
this->hide();
ss->show();
}
}
QVector<QString> SelectOS::getosName(){
so = new SelectOS();
return so->osName;
}
Window2.cpp
void SelectSoftware::getSoftwareDetails()
{
SelectOS *so = new SelectOS();
SelectSoftware *ss = new SelectSoftware();
ss->os = so->getosName();
QString fileName = ss->os + "/" +SOFTWARELIST; // Here I get the error...
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
QString msg = "Could not find the file " + fileName;
errorExit(msg);
}
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
processLine(line.toLower());
}
}
Help me, thanks ...
Assuming SOFTWARELIST is a simple QString:
QString fileName = QString( "%1/%2" )
.arg( ss->os.last() )
.arg( SOFTWARELIST );
This means you are creating a QString with placeholders %1 and %2 where %1 will be replaced by the result of ss->os.last() which returns the last item in the vector and %2 will be replaced by whatever SOFTWARELIST is.
If SOFTWARELIST is a vector as well, you will need to call e.g. .last() on it as well.
QVector is a container class, which holds set of something. In your example set of QString's. So then you try to form a fileName which is a QString you obviously cannot add to a fileName QString list of other Qstring's. (truly saying you can, but not with '+' operator and slightly different code).
Honestly I didn't got straight away why you actually passing QVector if you only need an application path I would suggest to use just QString.

Compilation warning while using codepad.org and devcpp

I am writting a program to check weather a given string is a palindrome. When I am trying to compile the code I got the below warning as
pandridom_with_space.cpp [Error] ISO C++ forbids comparison between pointer and integer [-fpermissive]
I know we can ignore this warning but I want to know how I can modify my code to remove this warning.
bool isPalindrome(const char*p,int len)
{
if((p==NULL)||(len<1))
return false;
int i=0,j=len-1;
while(p[i]!=0 && i<j)
{
while((i<j)&&(p[i] == " "))// <<<===== here I am getting warning.
i++;
while((i<j)&&(p[j] == " "))// <<<===== here I am getting warning.
j--;
if(p[i]!=p[j])
return false;
i++;
j--;
}
return true;
}
p[i] == " "
p[i] is a char (which is an integer type), and " " is a (const, since it's C++) char array that is converted for the comparison to a pointer to its first element.
You meant to compare it to a space character, ' '. (Note the single quotes for a character literal, double quotes are for string literals.)

Resources