Serialization

serialization4ProtobufDemo

Path
pkg20serialization/src/main/java/pkg20serialization/serialization4ProtobufDemo.java
Package
pkg20serialization
Study order
4
Run
Maven module
Command
mvn -f pkg20serialization/pom.xml compile
Dependencies
com.google.protobuf.Struct, com.google.protobuf.Value, com.google.protobuf.util.JsonFormat

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg20serialization/src/main/java/pkg20serialization/serialization4ProtobufDemo.java
1package pkg20serialization;2 3import com.google.protobuf.Struct;4import com.google.protobuf.Value;5import com.google.protobuf.util.JsonFormat;6 7/*8 * serialization4ProtobufDemo.java — Protocol Buffers: compact binary schema-first format.9 * This demo uses protobuf Struct/Value (no protoc step required).10 */11public class serialization4ProtobufDemo {12 13    public static void main(String[] args) throws Exception {14        Struct struct = Struct.newBuilder()15                .putFields("name", Value.newBuilder().setStringValue("Ada").build())16                .putFields("id", Value.newBuilder().setNumberValue(42).build())17                .build();18 19        byte[] bytes = struct.toByteArray();20        System.out.println("Protobuf bytes length: " + bytes.length);21        System.out.println("JSON view: " + JsonFormat.printer().print(struct));22 23        Struct parsed = Struct.parseFrom(bytes);24        System.out.println("Parsed name: " + parsed.getFieldsOrThrow("name").getStringValue());25    }26}