Difference between Protocol Buffers (protobuf) and JSON serialization ?

#json

Answer

Overview

Protocol Buffers (protobuf) and JSON are two different data serialization formats used to transfer data between services. Protobuf is binary and compact; JSON is text and human-readable.


JSON Serialization

dart
import 'dart:convert';

// Dart object → JSON string
final user = {'name': 'Alice', 'age': 28};
final jsonStr = jsonEncode(user);  // '{"name":"Alice","age":28}'

// JSON string → Dart object
final decoded = jsonDecode(jsonStr); // Map<String, dynamic>

JSON payload size example:

json
{"name":"Alice","age":28,"email":"alice@example.com"}
// 52 bytes (text)

Protocol Buffers (protobuf)

protobuf
// user.proto — schema definition
syntax = "proto3";

message User {
  string name = 1;
  int32 age = 2;
  string email = 3;
}
dart
// Flutter — using protobuf package
import 'user.pb.dart';

// Serialize to binary
final user = User()
  ..name = 'Alice'
  ..age = 28
  ..email = 'alice@example.com';

final bytes = user.writeToBuffer(); // Binary — ~10-15 bytes

// Deserialize from binary
final decoded = User.fromBuffer(bytes);
print(decoded.name); // Alice

Protobuf payload size for same data: ~15 bytes (binary) vs 52 bytes (JSON)


Key Differences

FeatureJSONProtocol Buffers
FormatText (human-readable)Binary (machine-readable)
SizeLarger (~30–50% bigger)Smaller (3–10x smaller)
SpeedSlower (parse text)Faster (binary parsing)
SchemaNone requiredRequired (
text
.proto
files)
Human-readable✅ Yes❌ No
Debugging✅ Easy (read in tools)❌ Hard (need decode)
Language supportUniversalRequires generated code
Backward compatibility❌ Manual✅ Built-in (field numbers)
Used inREST APIs, webgRPC, high-performance services

When to Use Which

Use CaseRecommendation
Public REST APIJSON
Mobile ↔ Backend (standard apps)JSON
High-performance microservicesProtobuf
Real-time games / streamingProtobuf
IoT with bandwidth constraintsProtobuf
gRPC communicationProtobuf (required)
Debugging-friendly APIJSON

Performance Comparison

MetricJSONProtobuf
Payload size100%30–70% of JSON
Serialization speedModerate3–5x faster
Deserialization speedModerate3–5x faster
Network transferSlowerFaster

Setup for Flutter (protobuf)

yaml
dependencies:
  protobuf: ^3.1.0

dev_dependencies:
  protoc_plugin: ^21.1.2
bash
# Generate Dart code from .proto file
protoc --dart_out=lib/generated lib/proto/user.proto

Summary: Use JSON for most Flutter REST APIs — it's simpler and universally compatible. Use Protobuf when you need maximum performance, minimum payload size, or are using gRPC.