retrofit and orm library throw StackOverflow

前端 未结 2 1496
醉酒成梦
醉酒成梦 2021-01-25 12:17

I try to use 2 libraries:

  • square/Retrofit - Rest client
  • satyan/sugar - db orm

retrofit use gson, so do class



        
相关标签:
2条回答
  • 2021-01-25 12:31

    Your POJO class need a empty constructor :

    you shoud add this constructor to your Book class:

    public Book(){
    
    }
    
    0 讨论(0)
  • 2021-01-25 12:34

    Error happens when Gson tries to resolve type information about an object it have to deserialize. It gets into an infinite recursion due to the cyclic reference to your Book class in extends declaration.

    However even if Gson could cope with your class, I would not recommend using these libs combination.

    You see, what Gson does is much alike to what standard Java serialization does but in JSON format. I mean that Gson takes the internal state of your object and performs its serialization. And when it parses JSON it creates an object with the state specified in this JSON.

    If you take a look at SugarRecord class, you'll see that it has a field named "tableName". Thus if you passed your Book object to Gson instance, you'd get

    {name: "book name", tableName: "table_book"}.

    Moreover, if you got a response from server which is like

    {name: "another book name", tableName: "something absolutely unrelated"},

    you would get an instance of Book with a state exactly matching what is described in this response. Meaning, with tableName being not equal to what you would like...

    You could workaround this issue using exclusion strategies in Gson, but overall you'll get yet another problem.

    P.S. After a quick look at SugarRecord class on github I do not understand why it has a type parameter at all. It's even not used really. Thus technically I think you'll be able to combine these 2 libraries, if you skip type parameter in extends declaration making your class look like class Book extends SugarRecod { }, and use an exclusion strategy. Yet, I wouldn't do it myself in practice :).

    0 讨论(0)
提交回复
热议问题