Class Structor

java.lang.Object
com.google.mu.protobuf.util.Structor

@CheckReturnValue @RequiresProtobuf public class Structor extends Object
A helper that makes Structs and Values from POJOs. Useful for converting Json data to Struct. For example:

 Map<String, ?> jsonData = ...;
 Struct struct = new Structor().struct(jsonData);
 

It can also be used to create a heterogeneous Struct literal like:


 Struct ironMan = new Structor()
     .struct(
         "name", "Tony Stark",
         "age", 10,
         "known_as", List.of("Iron Man", "Genius"));
 

Or if your structs have many more fields, consider to use the toStruct() BiCollector, as in:


 BiStream.of("k1", 1, "k2", 2, "k3", 3, "k4", 4, ...)
     .collect(new Structor().toStruct());
 

For simple scenarios, prefer to use MoreStructs to create Struct. Its single-field struct() factory methods are more efficient, can be static imported, and unsupported types cause compilation error as opposed to runtime exception.

The toValue(java.lang.Object) method is responsible for converting POJO to Value, and recursively, the Collections, Maps and Tables thereof into corresponding ListValue or Struct wrappers.

You can create a subclass to implement custom mapping. For example, if the application needs to map User types to Value by using the user ids:


 Structor customStructor = new Structor() {
   public Value toValue(Object obj) {
     if (obj instanceof User) {  // custom logic
       return toValue(((User) obj).getId());
     }
     return super.toValue(obj);  // else delegate to default implementation
   }
 };
 
This custom mapping logic will be applied recursively to Iterable elements, Map keys/values, and all other supported collection types.
Since:
5.8