Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serialization of array of not same model items #712

Closed
Haaxor1689 opened this issue Aug 25, 2017 · 2 comments
Closed

Serialization of array of not same model items #712

Haaxor1689 opened this issue Aug 25, 2017 · 2 comments

Comments

@Haaxor1689
Copy link

When trying to serialize json string that contains array of elements that have a different model, serialization throws first time it encounters a different type for the same key. Simplified example of my situation is below:

[
  {
    "id": 0,
    "name": "adsad"
  },
  {
    "id": "123",
    "name": "aawew"
  }
]

Is there a way to parse such json string?

@nlohmann
Copy link
Owner

There is no problem with this. This program parses your input and prints it:

#include "json.hpp"
#include <iostream>

using json =  nlohmann::json;

int main() {
    std::string text = R"([
    {
        "id": 0,
        "name": "adsad"
    },
    {
        "id": "123",
        "name": "aawew"
    }
    ])";
    
    json j = json::parse(text);
    
    std::cout << std::setw(2) << j << std::endl;
}

Output:

[
  {
    "id": 0,
    "name": "adsad"
  },
  {
    "id": "123",
    "name": "aawew"
  }
]

What is your error message?

@Haaxor1689
Copy link
Author

Haaxor1689 commented Aug 26, 2017

So I've solved this issue now. I was getting the error in from_json method that converts that json to my model class.

class Model {
    int id;
    std::string name;
}

Solution was pretty straightforward once I found out that I can check the type of data that lies in json type on runtime with this simple function:

int getInt(const json& value) {
    return value.is_string() ? std::stoi(value.get<std::string>()) : value.get<int>();
}

So because I know that the value for id should be int but is sometimes saved as a string I just call this function when reading the value in from_json function.

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

No branches or pull requests

2 participants