0

Player Object Model

In the Player Model, I want to save the JSON response so that I will get any new computed properties in the future without changing the schema.

But here, I'm getting the error to save the json of type [String: Any].

Any alternative or recommendations...?

  • Welcome to SO. It’s a good idea to include code, errors and and structures as *text*, not links and images. That way, if they are needed in an answer, they can be copied and pasted. Also, if the links break, it would invalidate the question. See [images and links are evil](http://idownvotedbecau.se/imageofcode). Also, images are not searchable which may prevent future readers from locating the question. Take a look at [No Images Please](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) – Jay Jan 06 '23 at 18:12

1 Answers1

0

Any is not a supported value type of Map. Looking a the documentation for Map, which shows the definition

public final class Map<Key, Value>

value is a RealmCollectionValue can be one of the following types

This can be either an Object subclass or one of the following types: Bool, Int, Int8, Int16, Int32, Int64, Float, Double, String, Data, Date, Decimal128, and ObjectId (and their optional versions)

One option is to to use AnyRealmValue so it would look like this

class Player: Object {
    let json = Map<String, AnyRealmValue>()
}

here's how to populate the json with a string and an int

let s: AnyRealmValue = .string("Hello")
let i: AnyRealmValue = .int(100)

let p = Player()
p.json["key 0"] = s
p.json["key 1"] = i

then to get back the values stored in the map:

for key in p.json {
    let v = key.value

    if let s = v.stringValue {
        print("it's a string: \(s)")
    } else if let i = v.intValue {
        print("it's an int: \(i)")
    }
}

and the output

it's a string: Hello
it's an int: 100
Jay
  • 34,438
  • 18
  • 52
  • 81
  • In the above example, you are constructing the JSON object and inserted in the "json". But I need to assign the JSON object which is received from the API response to the "json" property without parsing. E.g. I want to store the following JSON {"name": "StackOverflow", "age": 24, "cgpa": 7.4, "subject": ["maths", "science", "physics", "chemistry"] } in the "json" property – ping2karthikeyan Jan 09 '23 at 06:14
  • @ping2karthikeyan I see. Unfortunately, that won't work with Realm directly. Realm does not have nor support `ANY` and the closest option, as mentioned in the answer is `AnyRealmValue`. You may be able to do something with [Type Projections](https://www.mongodb.com/docs/realm/sdk/swift/model-data/define-model/supported-types/#map-unsupported-types-to-supported-types) but remember - Realms' ability to persist data relies on the `Object` type, and there are [Supported Property Types](https://www.mongodb.com/docs/realm/sdk/swift/model-data/define-model/supported-types/#supported-property-types) – Jay Jan 09 '23 at 18:04