Struct with JSON in C ++

0

I'm having problems inflating a struct using a JSON file, in fact I do not know how to do this, I've been searching the JsonCpp library, but I was not successful.

Here's 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,
        }
    }
}
    
asked by anonymous 08.12.2018 / 23:25

1 answer

0

Actually it is not possible to "inflate" a struct since this term defines a data structure or data type. What you will want to do is to fill a container with objects of the type of your struct. Another thing ... it will be tricky 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 it would be simpler:

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

If it can be this json then it becomes easy to populate a container of type vector with objects of the type of 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; 
} 
    
09.12.2018 / 02:14