Skip to content

Serialization of array of not same model items #712

Closed

Description

@Haaxor1689

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?

Activity

  1. nlohmann commented on Aug 26, 2017

    @nlohmann
    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?

  2. Haaxor1689 commented on Aug 26, 2017

    @Haaxor1689
    Author

    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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions