简体   繁体   中英

Thrift type modelling for List<HashMap<String,Object>>

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.

AFAIK thrift does not directly support generic Object types which can be type casted to/from any object you like. You'll have to specifically define your object as in above example. You can't have a return type as Object. There's a work around mentioned here: Generic objects in Apache Thrift

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM