Skip to content

How to convert JSON to Struct with embeded subject #1310

Description

@mahuichao

I am very glad to see this library and thanks for ur effort .I will make my problem short:
if I have a json like:
{
"SentenceStressScore": 54,
"WordsStressScore": 54,
"consonant_score": 54,
"words_info": [{
"score": 50,
"word": "HOW"
}, {
"score": 50,
"word": "ARE"
}, {
"score": 50,
"word": "YOU"
}]
}

and I want to use struct to get it,here is my code:
`#include
#include
#include
#include "json.hpp"

using json=nlohmann::json;
using namespace std;

struct words{
float score;
float word;
};

struct gop{
float SentenceStressScore;
float WordsStressScore;
float consonant_score;
vector words_info;
};

void to_json(json&j, gop& g){
    j=json{{"SentenceStressScore",g.SentenceStressScore},{"WordsStressScore",g.WordsStressScore},{"consonant_score",g.consonant_score},{"words_info",g.words_info}}
}
void from_json(const json& j, gop& g) {
    j.at("SentenceStressScore").get_to(g.SentenceStressScore);
    j.at("WordsStressScore").get_to(g.WordsStressScore);
    j.at("consonant_score").get_to(g.consonant_score);
    j.at("words_info").get_to(g.words_info);
}

int main(){
string s2="{ "SentenceStressScore": 54,"WordsStressScore": 54,"consonant_score": 54, "words_info": [{"score": 50, "word": "HOW"}, {"score": 50, "word": "ARE" }, { "score": 50, "word": "YO"}]}";

    auto j2=json::parse(s2);
    gop g=j2;
    cout<<g.SentenceStressScore<<endl;

}`
But this is wrong ,I can't find how to do it? help,pz,I appreciate.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    state: needs more infothe author of the issue needs to provide more details

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions