Skip to content

Commit

Permalink
try using nlohmann-json to parse json data
Browse files Browse the repository at this point in the history
  • Loading branch information
110CodingP committed Apr 26, 2024
1 parent 32a5e00 commit 628693a
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
10 changes: 10 additions & 0 deletions test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[
{
"Name": "Test",
"Val": "TestVal"
},
{
"Name": "Test2",
"Val": "TestVal2"
}
]
Binary file added trying_nlohman_json
Binary file not shown.
36 changes: 36 additions & 0 deletions trying_nlohman_json.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#include <iostream>
#include <string>
#include <stdexcept>
#include <json.hpp>
#include <fstream>

using json = nlohmann::json;

struct Test {
std::string Name;
std::string Val;
};

void from_json(const json& j, Test& p) {
j.at("Name").get_to(p.Name);
j.at("Val").get_to(p.Val);
}

template <typename T, size_t N>
void from_json(const json& j, T (&t)[N]) {
if (j.size()!=N) {
throw std::runtime_error("size!");
}
size_t index=0;
for (auto& item : j) {
from_json(item, t[index++]);
}
}
int main() {
std::ifstream f("test.json");
json data = json::parse(f);
Test my_array[2];
from_json(data, my_array);
std::cout<<my_array[0].Name<<std::endl;
return 0;
}

0 comments on commit 628693a

Please sign in to comment.