Objectmapper gets an array from a single element in JSON

So, I have the following JSON which I use together with ObjectMapper and Realm.

{ "result": [ { "id": 20, "types": [ "now" ], "url": "/nl/whereto/ezrhgerigerg", "categories": [ { "id": 39, "name": "Food " }, { "id": 21, "name": "Varia" } ] }, 

My problem is getting data from "types", which say "now" or "later" for some elements of the array and are empty for other elements (therefore, the type element is not specified).

I tried to do the following in my mapping:

 class Publication: Object, Mappable { dynamic var id:Int = 0 var typez = List<getType>() dynamic var url:String? required convenience init?(_ map: Map) { self.init() } override static func primaryKey() -> String? { return "id" } func mapping(map: Map) { id <- map["id"] typez <- map["types"] url <- map["url"] } } class getType: Object, Mappable { dynamic var text: String = "" required convenience init?(_ map: Map) { self.init() } func mapping(map: Map) { text <- map[""] } } 

When I check the Realm database, you can see that the typez array [getType] was created, but it is empty for all elements (even those where the types are "now"). The remaining two elements (id and url) are populated in the database.

What am I doing wrong so that it is not saved in the database?

+1
source share
1 answer

Because Realm cannot determine the purpose of the List properties, because the List property is not Objective-C. Thus, List properties must be declared as let and must not be nil . You should use append / remove ... / insert ... method to modifying the List`.

So your code

 typez <- map["types"] 

does not work, since you directly assign values ​​to the typez property.

The workaround is as follows:

 func mapping(map: Map) { ... var typez: [String]? = nil typez <- map["types"] typez?.forEach { t in let obj = getType() obj.text = t self.typez.append(obj) } ... 

First save the displayed value in a local variable (this is a string array). Then convert the array of strings to objects. Then add the objects to the List property.

+1
source

Source: https://habr.com/ru/post/1247882/


All Articles