Search code examples
groovygsontraits

How to serialize groovy traits with Gson


I got a class implementing a trait which i want to serialize:

package com.company.project.model.v2

import com.company.project.traits.v2.TOpeningTimes

class Gasstation extends Poi implements TOpeningTimes {

    String brand
    double diesel
    double e5
    double e10
}

the trait class is:

package com.company.project.traits.v2

import com.company.project.model.OpeningTime

trait TOpeningTimes {

    List<OpeningTime> openingTimes
    boolean isOpen

}

I use gjson to serialize objects. I added an adapter to serialize geometries from LTS, all works fine but since i use traits gjson serializes something like this:

{
    "brand":"AVIA Xpress", 
    "diesel":1.709, "e5":1.789,
    "e10":1.729,
    "com_company_project_traits_v2_TOpeningTimes__isOpen":true,
    "point": {
        "type":"Point",
        "coordinates":[8.2379,48.9507],
        "crs": {
            "type":"name",
            "properties":{ 
                "name":"EPSG:4326"}
            }
        },
    "type":"GASSTATION",
    "address": {
        "city":"Berlin",
        "houseNumber":"1",
        "street":"Flixstreet"
    }
}

Does anyone know how to make gson handle traits? thx

I tried to serialize goovy traits and expected it works like serializing classes but it doesn't


Solution

  • Using gson Annotations worked!

    package com.company.project.traits.v2
    
    import com.company.project.model.OpeningTime
    
    trait TOpeningTimes {
    
    
        @SerializedName("openingTimes")
        List<OpeningTime> openingTimes
    
        @SerializedName("isOpen")
        boolean isOpen
    
    }