Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map JSON to array of my model - ObjectMapper

I am having the trouble in mapping json to my objects array with ObjectMapper. Here is my model object.

class Participant : Mappable {

var user_global_id: String!
var user_app_id: String!

init(){
}

required init?(_ map: Map) {
}

// Mappable
func mapping(map: Map) {
    user_global_id    <- map["user_global_id"]
    user_app_id    <- map["user_app_id"]
}
}

And my json looks: "[{\"user_global_id\":5093363330056192,\"user_app_id\":11}]"

I am calling ObjectMapper:

let participants = Mapper<[Participant]>().map(json["registeredParticipants"])

Above line gives error: Type '[Participant]' does not conform to protocol 'Mappable'

like image 530
Shalva Avanashvili Avatar asked Jun 16 '16 10:06

Shalva Avanashvili


People also ask

How do I read JSON file with ObjectMapper?

Read Object From JSON via URL ObjectMapper objectMapper = new ObjectMapper(); URL url = new URL("file:data/car. json"); Car car = objectMapper. readValue(url, Car. class);

Can we convert JSON to map?

We can easily convert JSON data into a map because the JSON format is essentially a key-value pair grouping and the map also stores data in key-value pairs. Let's understand how we can use both JACKSON and Gson libraries to convert JSON data into a Map.

What does ObjectMapper readValue do?

The simple readValue API of the ObjectMapper is a good entry point. We can use it to parse or deserialize JSON content into a Java object. Also, on the writing side, we can use the writeValue API to serialize any Java object as JSON output.


1 Answers

The main mistake is in passing the array as generic attribute. Here is the solution

 Mapper<Participant>().mapArray(json["registeredParticipants"])
like image 94
Shalva Avanashvili Avatar answered Sep 27 '22 22:09

Shalva Avanashvili