【问题标题】:CPP REST SDK JSON - How to create JSON w/ Array and write to fileCPP REST SDK JSON - 如何使用数组创建 JSON 并写入文件
【发布时间】:2017-06-16 20:30:54
【问题描述】:

我在使用 CPP REST SDK 的 JSON 类时遇到问题。我不知道何时使用json::valuejson::objectjson::array。尤其是后两者看起来很像。 json::array 的用法对我来说也很不直观。最后,我想将 JSON 写入文件或至少写入 stdcout,以便检查它是否正确。

使用 json-spirit 对我来说要容易得多,但因为我想稍后发出 REST 请求,所以我想我可以省去字符串/wstring 的疯狂并使用 CPP REST SDK 的 json 类。

我想要实现的是这样的 JSON 文件:

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

这是我试过的代码:

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;

我真的需要这个额外的计数器变量i吗?显得比较不雅。使用 json::array/json::object 会让事情变得更好吗?以及如何将我的 JSON 写入文件?

【问题讨论】:

    标签: json cpprest-sdk


    【解决方案1】:

    这可以帮助你:

    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"));
    

    如果你想创建列表,比如bobList,你真的需要使用一些迭代器变量。 否则你只会得到一堆单独的变量。

    为了输出到控制台使用

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

    最后,这将导致

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

    【讨论】:

    • 很好的答案,帮助很大。仅供参考,您可以使用wcout 而不是cout,然后您就不需要c_str() 方法来打印到控制台。
    • 而不是L"something",使用U("something") 会更好,这样它就可以在Linux 和Windows 上构建而不会出现任何问题。这段代码不会像这样在 Linux 下编译。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 2017-10-02
    • 2018-07-04
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    相关资源
    最近更新 更多