Java.Serialization.JSON.XML

🚀 While Java’s built-in binary serialization (Serializable) is powerful, you often want to serialize objects to readable and interoperable formats like JSON, XML, or YAML, especially for:

  • APIs
  • Config files
  • Cross-platform communication (e.g., Java ↔ Python)

Let’s walk through the popular formats and tools 👇

📦 1. JSON Serialization (Most Popular)
✅ Libraries:
Gson (by Google)

Jackson

org.json

🧪 Example with Jackson:

✅ Pros:

  • Human-readable
  • Works across languages (Java, Python, JS, etc.)
  • Handles nested objects, lists, maps
  • Easily customizable with annotations: @JsonProperty, @JsonIgnore, etc.

🧾 2. XML Serialization

✅ Libraries:

  • JAXB (Java built-in since Java 6)
  • XStream

🧪 Example with JAXB:

@XmlRootElement
public class User {
    public String name;
    public int age;
}

// Serialize
JAXBContext context = JAXBContext.newInstance(User.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(user, new File("user.xml"));

Result:

<User>
    <name>Stanley</name>
    <age>33</age>
</User>

✅ Pros:

  • Standardized
  • Schema support (XSD)
  • Good for enterprise/legacy systems

🧵 3. YAML Serialization

✅ Libraries:

🧪 Example:

Yaml yaml = new Yaml();
String output = yaml.dump(user);  // name: Stanley\nage: 33
User restored = yaml.load(output);

✅ Pros:

  • More readable than JSON for configs
  • Used in DevOps tools, CI/CD, etc.

🔐 4. Binary Serialization (Custom)

✅ Libraries:

  • Protobuf (Google)
  • Avro (Apache)
  • Kryo (fastest in Java)
  • FlatBuffers

Example with Protobuf:

  • Define schema:
message User {
  string name = 1;
  int32 age = 2;
}
  • Then compile to Java and use generated classes.

✅ Pros:

  • Super compact and fast
  • Cross-platform
  • Ideal for microservices, network communication

⚙️ 5. Manual Custom Format

You can use DataOutputStream, BufferedWriter, or FileWriter to write your own format.

Example:

writer.write("username=" + user.name + "\n");
writer.write("age=" + user.age + "\n");

✅ Good for simple use cases
❌ Hard to maintain


🧵 TL;DR: Compare Formats

FormatReadableCross-LangSizeSpeedGood For
JSONMediumFastAPIs, Web, Config
XMLLargeSlowerLegacy systems, strict schemas
YAMLMediumMediumConfigs, readable files
Protobuf✅ Small✅ Super fastNetwork, microservices
Java Serializable❌ Java onlyMediumFast (in-JVM)Internal storage
Manual⚠️⚠️VariesVariesSimple/controlled formats
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.