Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

thrift

I've a service method in Java with following return type:

List<HashMap<String,Object>>

How can I best model it in thrift?

like image 935
thinley Avatar asked Feb 15 '23 06:02

thinley


1 Answers

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.

like image 163
JensG Avatar answered Feb 23 '23 12:02

JensG