I've a service method in Java with following return type:
List<HashMap<String,Object>>
How can I best model it in thrift?
Pretty straightforward:
struct MyObjectData {
// data of your objects
}
list< map< string, MyObjectData>>
You may want to make it a type:
typedef list< map< string, MyObjectData>> MyObjectStructure
The caveat lies in the data structure of MyObjectData
. If by Object
you literally mean any Object
, then we've got a problem. Thrift can't handle generic cases like this, because it does not support structures derived from each other (like you can do with class
). What you can do is, to use a union
holding different kinds of structs, where only one is used at a time:
struct Foo { /* some fields */ }
struct Bar { /* some fields */ }
// a union allows us to store different kinds of structs in one list
union Generic {
1: Foo foo
2: Bar bar
}
// technically, a union is more or less a struct with optional fields,
struct Alternative {
1: optional Foo foo
2: optional Bar bar
}
In case you need derived structures, I have solved this problem for me by doing this:
struct Base {
// some fields
}
struct Derived {
1: Base base_
// some more fields
}
which works quite well for me. If you have a deep inheritance tree, it might become somewhat painful to work with, but that's not the case in my particular case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With