2012-11-08 13 views
14

Ho seguente codice:Crea un array JSON vuoto con jsoncpp

void MyClass::myMethod(Json::Value& jsonValue_ref) 
{ 
    for (int i = 0; i <= m_stringList.size(); i++) 
    { 
     if (m_boolMarkerList[i]) 
     { 
      jsonValue_ref.append(stringList[i]); 
     } 
    } 
} 


void MyClass::myOuterMethod() 
{ 
    Json::Value jsonRoot; 
    Json::Value jsonValue; 

    myMethod(jsonValue); 

    jsonRoot["somevalue"] = jsonValue; 
    Json::StyledWriter writer; 
    std::string out_string = writer.write(jsonRoot); 
} 

Se tutti boolMarkers sono false l'out_string è { "somevalue": null} ma io voglio che sia un array vuoto: { "somevalue" : []}

Qualcuno sa come ottenere ciò?

Grazie mille!

risposta

27

si può fare anche in questo modo:

jsonRootValue["emptyArray"] = Json::Value(Json::arrayValue); 
+8

perché non solo 'jsonRootValue [" emptyArray "] = Json :: arrayValue'; –

+1

Penso che forse quando ho postato questa domanda - due anni prima del tuo commento - non era possibile. –

3

OK, ho capito. È un po 'fastidioso, ma dopo tutto è abbastanza facile. per creare un array JSON vuoto con jsoncpp:

Json::Value jsonArray; 
jsonArray.append(Json::Value::null); 
jsonArray.clear(); 
jsonRootValue["emptyArray"] = jsonArray; 

uscita via scrittore sarà:

{ "emptyArray" = [] }   
6

È possibile fare questo definendo l'oggetto Value come un "oggetto Array" (per impostazione predefinita lo rende come un oggetto "oggetto" che è il motivo per cui il tuo membro diventa "null" quando non viene effettuata alcuna assegnazione, invece di [])

Quindi, passare questa linea:

Json::Value jsonValue; 
myMethod(jsonValue); 

con questo:

Json::Value jsonValue(Json::arrayValue); 
myMethod(jsonValue); 

E voilà! Si noti che è possibile cambiare "arrayValue" in qualsiasi tipo desiderato (oggetto, stringa, array, int ecc.) Per creare un oggetto di quel tipo. Come ho detto prima, quello predefinito è "oggetto".

+0

Grazie Ahmet, ma questo è esattamente lo stesso di user609441 già dichiarato con un po 'più di testo. –

+1

Volevo spiegare anche i motivi^_ ^ –