Moshi: Exclusion without Transient

Created on 26 Feb 2018  路  4Comments  路  Source: square/moshi

Is there any (hopefully somewhat simple) way to exclude fields in Kotlin without using @Transient?

I am using ObjectBox for persistence and it utilizes different types for relationships, currently the preferred solution seems to be to deserialize into a list and then post process to build the relationships before persistence. My problem is that if Moshi sees the original fields it throws an error since it can't generate those types, but using @Transient causes ObjectBox to throw an error as it needs to generate some code it cannot generate on a transient field. Is there a simple way around this I am missing?

Most helpful comment

Please do not use the same types for JSON and persistence. It鈥檚 a nice shortcut today but it will cause you grief if your application grows more complex.

All 4 comments

Please do not use the same types for JSON and persistence. It鈥檚 a nice shortcut today but it will cause you grief if your application grows more complex.

I don't really think that argument has anything to do with my question, but thanks for the advice. Using transient on certain fields also means we can't serialize them for any other purpose, which is still inconvenient. It doesn't make a lot of sense to me that if I want to serialize the exact same data at any point for any purpose I have to make another almost identical object first.

My question is simply is @Transient the only way to tell Moshi to ignore a field in a data class?

Yes.
Two other options: Make a custom JsonAdapter for the type. Copy the KotlinJsonAdapter into your codebase and modify it for your logic. It's very small.

(In any case, my experience aligns with Jesse's advice.)

That may just be exactly what I am looking for. Thank you.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rephiscorth picture rephiscorth  路  5Comments

kapil93 picture kapil93  路  4Comments

rephiscorth picture rephiscorth  路  5Comments

trevjonez picture trevjonez  路  4Comments

ayedo picture ayedo  路  4Comments