将POJO转换为协议缓冲请求消息

时间:2015-08-07 21:25:52

标签: java android protocol-buffers retrofit

而不是使用Relationship.RelationshipGetRequest作为请求和响应。有没有办法将请求/响应转换为POJO?

我已经看过这个解决方案,但它比我正在寻找的要复杂一点: Converting a Protocol Buffer to a POJO

我使用的是Retrofit和Google Protocol Buffers。

我有什么:

public interface RelationshipService {

    @POST("/relation/get")
    Observable<Relationships.RelationshipGetResponse> getRelationship(
            @Body() Relationship.RelationshipGetRequest request
    );
}

我想用什么:

public interface RelationshipService {

    @POST("/relation/get")
    Observable<Relationship> getRelationship(
            @Body() Relationship request
    );
}

关系:

public class Relationship {
    private long mRelationshipId;
    private String mName;
    // etc. about 10 other properties..
}

我的请求最终会像这样,必须在此处构建请求..

mClient.createService(RelationshipService.class).getRelationship(Relationships.RelationshipGetRequest.newBuilder().setRelationshipId(-1).build()).subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<Relationships.RelationshipGetResponse>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Timber.e(e, "Error! " + e.getMessage());
            }

            @Override
            public void onNext(Relationships.RelationshipGetResponse relationship) {

                String output = relationsip.getRelationship().getName();
                Timber.i(output);
            }
        });

2 个答案:

答案 0 :(得分:0)

您必须编写自己的适配器以将protobuff消息转换为POJO实例。否则,您可以尝试protostuff,您可以将现有的POJO用作模式。 检查一下: https://github.com/anirbanroy88/services/tree/master/protostuff

答案 1 :(得分:0)

我解决了我的问题。我过度使这个问题复杂化,而不是正确的思考方向。 如果有人遇到这个问题,这是我的解决方案的伪代码。

public interface RelationshipService {

     @POST("/relation/get")
        Observable<RelationshipResponse> getRelationship(@Body() RelationshipRequest request);
}


// API Manager class

RelationshipService service = mRestAdapter.createService(RelationshipService.class);

public Observable<Relationship> getRelationship(final long id) {
    RelationshipRequest request = Builder()
    .relationshipId(id)
    .build;

    return service.getRelationship(request)
    .subscribeOn(Schedulers.newThread())
    .observeOn(AndroidScheduler.mainThread())
    .map(new Func1(RelationshipResponse response, Relationship relationship) {
        return buildRelationship(response);
    }); 
}