#java #key-value #properties

serde-java-properties

Serde support for java-properties

3 unstable releases

0.2.0 Apr 29, 2024
0.1.1 Jul 25, 2023
0.1.0 Jan 9, 2022

#408 in Encoding

Download history 200/week @ 2024-06-10 49/week @ 2024-06-17 81/week @ 2024-06-24 106/week @ 2024-07-01 74/week @ 2024-07-08 122/week @ 2024-07-15 129/week @ 2024-07-22 86/week @ 2024-07-29 86/week @ 2024-08-05 103/week @ 2024-08-12 81/week @ 2024-08-19 103/week @ 2024-08-26 61/week @ 2024-09-02 64/week @ 2024-09-09 139/week @ 2024-09-16 142/week @ 2024-09-23

424 downloads per month
Used in 3 crates (2 directly)

MIT license

41KB
903 lines

Serde Java Properties

Docs License Version

Java Properties is a simple, line-oriented format for specifying key-value resources used in Java programs. This crate offers basic (de-)serializers for use with serde-enabled datastructures.

field_a: a value
field_b: 100
field_c: true

Implementation

Internally, the java-properties crate is used for iterating key-value pairs in an input stream, and writing key-value pairs to an output stream.

Deserializing a struct

Usually, the format is untyped i.e. it deserialises to a map from String to String. This crate uses the default std::str::FromStr implementations for integers, floats and booleans to provide a typed interface on top of that. That way, simple structures or maps that implement serde::Deserialize can be loaded from properties files.

use serde::Deserialize;

#[derive(Debug, PartialEq, Deserialize)]
struct Data {
    field_a: String,
    field_b: usize,
    field_c: bool,
}
let text = "
field_a: a value
field_b: 100
field_c: true
";

let data: Data = serde_java_properties::from_str(text).unwrap();

assert_eq!(data.field_a, "a value");
assert_eq!(data.field_b, 100);
assert_eq!(data.field_c, true);

Serializing a struct

Serialization uses the default std::fmt::Display implementations for each primitive type.

Supported in the top-level Serializer:

  • Maps
  • Structs
  • Enums of struct variants
  • Options of all of these

Supported in the field-level Serializer:

  • Integers (i8, i16, i32, i64, u8, u16, u32, u64)
  • Floats (f32, f64)
  • Booleans (true or false)
  • Strings
  • Enums of unit variants
  • Options of all of these
use serde::Serialize;

#[derive(Debug, PartialEq, Serialize)]
struct Data {
    field_a: String,
    field_b: usize,
    field_c: bool,
}

let data = Data { field_a: "value".to_string(), field_b: 100, field_c: true };
let string = serde_java_properties::to_string(&data).unwrap();

assert_eq!(string, "field_a=value\nfield_b=100\nfield_c=true\n");

Alternatives

Similar to the java-properties crate itself, this crate is supposed to be an exact match to the format as specified in Java. If you need a more powerful configuration syntax, that supports nested structs, you should probably use HOCON.

Dependencies

~7MB
~182K SLoC