2015-07-28 12 views
10

https://msdn.microsoft.com/library/jj950082.aspx ha il seguente codice.C++ REST SDK (Casablanca) web :: json iteration

void IterateJSONValue() 
{ 
    // Create a JSON object. 
    json::value obj; 
    obj[L"key1"] = json::value::boolean(false); 
    obj[L"key2"] = json::value::number(44); 
    obj[L"key3"] = json::value::number(43.6); 
    obj[L"key4"] = json::value::string(U("str")); 

    // Loop over each element in the object. 
    for(auto iter = obj.cbegin(); iter != obj.cend(); ++iter) 
    { 
     // Make sure to get the value as const reference otherwise you will end up copying 
     // the whole JSON value recursively which can be expensive if it is a nested object. 
     const json::value &str = iter->first; 
     const json::value &v = iter->second; 

     // Perform actions here to process each string and value in the JSON object... 
     std::wcout << L"String: " << str.as_string() << L", Value: " << v.to_string() << endl; 
    } 

    /* Output: 
    String: key1, Value: false 
    String: key2, Value: 44 
    String: key3, Value: 43.6 
    String: key4, Value: str 
    */ 
} 

Tuttavia, con C++ REST SDK 2.6.0, sembra che non c'è nessun metodo CBEGIN in JSON :: valore. Senza di esso, quale potrebbe essere il modo giusto per scorrere la chiave: i valori di un nodo JSON (valore)?

risposta

8

Sembra che la documentazione che avete elencato è ancorato alla versione 1.0:

Questo argomento contiene informazioni per il C++ REST SDK 1.0 (nome in codice "Casablanca"). Se si utilizza una versione successiva dalla pagina Web di Codeplex Casablanca, utilizzare la documentazione locale al numero http://casablanca.codeplex.com/documentation.

Dando uno sguardo al changelog per la versione 2.0.0, troverete questo:

rottura Change - cambiato il modo viene eseguita l'iterazione su array JSON e oggetti. Non è più un iteratore di std :: pair restituito. Invece c'è un iteratore separato per array e oggetti rispettivamente sulla classe json :: array e json :: object. Questo ci consente di migliorare le prestazioni e di adeguarci di conseguenza. L'iteratore dell'array restituisce json :: values ​​e l'iteratore dell'oggetto restituisce ora std :: pair.

Ho controllato il sorgente su 2.6.0 e hai ragione, non ci sono metodi iteratori per la classe di valore. Sembra che quello che devi fare è prendere la rappresentazione interna object dalla tua classe value:

json::value obj; 
obj[L"key1"] = json::value::boolean(false); 
obj[L"key2"] = json::value::number(44); 
obj[L"key3"] = json::value::number(43.6); 
obj[L"key4"] = json::value::string(U("str")); 

// Note the "as_object()" method calls 
for(auto iter = obj.as_object().cbegin(); iter != obj.as_object().cend(); ++iter) 
{ 
    // This change lets you get the string straight up from "first" 
    const utility::string_t &str = iter->first; 
    const json::value &v = iter->second; 
    ... 
}