How to return a list of custom objects on Objectif

2019-07-09 05:03发布

问题:

I'm working on an Android project which uses Google App Engine for backend as described here: Using Android & Google App Engine on Android Studio.

I have some model classes on the backend side like User and Item, and I'm trying to return a list of Items user has.

public List<Ref<Item>> getItems() {
    return items;
}

When I try to Sync Project with Gradle Files, I get this error:

Error:Execution failed for task ':backend:appengineEndpointsGetClientLibs'. There was an error running endpoints command get-client-lib: Parameterized type com.googlecode.objectify.Ref≤backend.model.Item> not supported.

I checked some other questions here and was able to build the project without errors by adding @ApiResourceProperty(ignored = AnnotationBoolean.TRUE) annotation to my getter method. But after adding this line, I cannot see this method on Android app side.

Any idea how to make it possible to get a list of Items on Android side?

回答1:

I did it by saving/retrieving object that contains serialized collection. Class Lesson implements Serializable.

Language.java

import java.io.Serializable;
import java.util.List;

import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Serialize;

@Entity
public class Language {

    @Id
    private String key;
    private String title;
    @Serialize
    private List<Lesson> lessons;  //here collection

    //getters/setters ommited
}

LanguageService.java

import static com.googlecode.objectify.ObjectifyService.ofy;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.Named;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import com.minspok.entity.Language;

@Api(name = "langapi", version = "v1", description = "langapi")

public class LanguageService {

    static{
        ObjectifyService.register( Language.class );
    }


    @ApiMethod(name = "get")
    public Language getLanguage(@Named("key") String key){
        Language language = ofy().load().key(Key.create(Language.class,  
                        key)).now();
        return language;
    }


    @ApiMethod(name = "create")
    public void createLanguage(Language language){
        ofy().save().entity(language);   
    }
}

Helpful reading: https://github.com/objectify/objectify/wiki/Entities