Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CPP REST SDK JSON - How to create JSON w/ Array and write to file

I'm having troubles with the JSON classes of the CPP REST SDK. I can't figure out when to use json::value, json::object and json::array. Especially the latter two seem very alike. Also the usage of json::array is rather unintuitive to me. Finally I want to write the JSON to a file or at least to stdcout, so I can check it is correct.

It was way easier for me to use json-spirit, but since I want to make REST requests later on I thought I'd save me the string/wstring madness and use the json classes of the CPP REST SDK.

What I want to achieve is a JSON file like this:

{
  "foo-list" : [
      {
        "bar" : "value1",
        "bob" : "value2"
      }
  ]
}

This is the code I tried:

json::value arr;
int i{0};
for(auto& thing : things)
{
  json::value obj;
  obj[L"bar"] = json::value::string(thing.first);
  obj[L"bob"] = json::value::string(thing.second);
  arr[i++] = obj;
}
json::value result;
result[L"foo-list"] = arr;

Do I really need this extra counter variable i? Seems rather inelegant. Would using json::array/json::object make things nicer? And how do I write my JSON to a file?

like image 898
DenverCoder21 Avatar asked Apr 05 '26 16:04

DenverCoder21


1 Answers

This could help you:

json::value output;
output[L"foo-list"][L"bar"] = json::value::string(utility::conversions::to_utf16string("value1"));
output[L"foo-list"][L"bob"] = json::value::string(utility::conversions::to_utf16string("value2"));

output[L"foo-list"][L"bobList"][0] = json::value::string(utility::conversions::to_utf16string("bobValue1"));
output[L"foo-list"][L"bobList"][1] = json::value::string(utility::conversions::to_utf16string("bobValue1"));
output[L"foo-list"][L"bobList"][2] = json::value::string(utility::conversions::to_utf16string("bobValue1"));

If you want to create list, like bobList, you really need to use some iterator variable. Otherwise you will get only bunch of separate variables.

For output to console use

cout << output.serialize().c_str();

And finally, this will lead to

{
   "foo-list":{
      "bar":"value1",
      "bob":"value2",
      "bobList":[
         "bobValue1",
         "bobValue1",
         "bobValue1"
      ]
   }
}
like image 124
Zdeno Pavlik Avatar answered Apr 08 '26 05:04

Zdeno Pavlik