Struct with JSON in C++

Asked

Viewed 441 times

1

I’m having problems inflating a struct using a JSON file, in fact I don’t know how to do it, I’ve been researching about the Jsoncpp library, but I was not successful.

Follow a simple example of my code:

#include <iostream>

using namespace std;

struct Itens{
    int id, tipo, valor;
};

int main() {

    funcaoEncherStruct();

    return 0;
}

void funcaoEncherStruct(){
    //Segue função aqui
}

JSON file:

{
    "Itens": {
        "Produto1": {
            "id": 1,
            "tipo": 1,
            "valor": 20,
        },
        "Produto2": {
            "id": 2,
            "tipo": 3,
            "valor": 33,
        },
        "Produto3": {
            "id": 3,
            "tipo": 6,
            "valor": 60,
        }
    }
}

1 answer

1


It is actually not possible to "inflate" a struct since this term defines a data structure or data type. What you’ll want to do is fill a container with objects like your struct. Another thing... it will be complicated to do what you want with this json file. The file defines an array of Items of three types, Product1, 2 and 3, I think would be simpler:

{ "Itens": 
  [
    { "id": 1, "tipo": 1, "valor": 20, }, 
    { "id": 2, "tipo": 3, "valor": 33, }, 
    { "id": 3, "tipo": 6, "valor": 60, } 
  ]
}

If you can be this json then it’s easy to popular a vector container with objects like your struct:

#include <iostream> 
#include <fstream>
#include <jsoncpp/json/json.h>

using namespace std; 

struct Item{ int id, tipo, valor; }; 

int main() { 
  vector<Item> containeritens;

  ifstream ifs("Arquivo.json");
  Json::Reader reader; 
  Json::Value obj;

  reader.parse(ifs, obj); 

  const Json::Value& itens = obj["Itens"]; 

  for (int i = 0; i < itens.size(); i++).{
    Item item;
    item.id = itens[i]["id"].asUInt();
    item.tipo = itens[i]["tipo"].asUInt();
    item.valor = itens[i]["valor"].asUInt();

    contairnerItens.pushback(item);
  }
  return 0; 
} 
  • I got it, I was able to open my eyes a little bit to it, when I say inflate a struct I say fill it, you know? I tried to compile the code and ran after some solution, but I found some incomplete or more techniques, the " Json::Reader " is not depreciated? It would not be: "Json::Charreaderbuilder", as I parse with this property?

  • But there is no way to fill a struct, struct only defines the type of data understand?

  • I understand, I already solved this riddle too, I used another library in which the documentation was more organized, but thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.