- Notifications
You must be signed in to change notification settings - Fork403
Serializing to JSON, XML and more
- (Recommended) Map to your own custom DTO types
- UnitsNet.Serialization.JsonNet with Json.NET (Newtonsoft)
- DataContractSerializer for XML
- DataContractJsonSerializer for JSON (not recommended)
- System.Text.Json (not yet implemented)
- Protobuf and other
[DataContract]compatible serializers - Backwards compatibility
The recommended approach is to create your own data transfer object types (DTO) and map to/fromIQuantity.
This way you are in full control of the shape of your JSON, XML, etc. and also any breaking changes or deprecations to UnitsNet.
It could be solved like this, storing the value, quantity name and unit name:
// Your custom DTO type for quantities.publicrecordQuantityDto(doubleValue,stringQuantityName,stringUnitName);// The original quantity.IQuantityq=Length.FromCentimeters(5);// Map to your custom DTO type.QuantityDtodto=new(Value:(double)q.Value,QuantityName:q.QuantityInfo.Name,UnitName:q.Unit.ToString());/* Serialize to JSON:{ "Value": 5, "QuantityName": "Length", "UnitName": "Centimeter"}*/stringjson=System.Text.Json.JsonSerializer.Serialize(dto);// Deserialize from JSON.QuantityDtodeserialized=System.Text.Json.JsonSerializer.Deserialize<QuantityDto>(json)!;// Map back to IQuantity.if(Quantity.TryFrom(deserialized.Value,deserialized.QuantityName,deserialized.UnitName,outIQuantity?deserializedQuantity)){// Take your quantity and run with it.}
Alternatively, you can choose to use our custom serializers to map to/fromIQuantity to JSON, XML etc.
We strive to avoid breaking changes, but we can't guarantee it.
varjsonSerializerSettings=newJsonSerializerSettings{Formatting=Formatting.Indented};jsonSerializerSettings.Converters.Add(newUnitsNetIQuantityJsonConverter());stringjson=JsonConvert.SerializeObject(new{Name="Raiden",Weight=Mass.FromKilograms(90)},jsonSerializerSettings);objectobj=JsonConvert.DeserializeObject(json);
JSON output:
{"Name":"Raiden","Weight": {"Unit":"MassUnit.Kilogram","Value":90.0 }}If you need to support deserializing into properties/fields of typeIComparable instead of typeIQuantity, then you can add
jsonSerializerSettings.Converters.Add(newUnitsNetIComparableJsonConverter());
All quantities and theIQuantity interface have[DataContract] annotations and can be serialized by the built-in XMLDataContractSerializer.
<Powerxmlns="http://schemas.datacontract.org/2004/07/UnitsNet"xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Value>1.20</Value> <Unit>Milliwatt</Unit></Power>
SerializingIQuantity with additional type information:
[DataContract][KnownType(typeof(Mass))][KnownType(typeof(Information))]publicclassFoo{[DataMember]publicIQuantityQuantity{get;set;}}// Serialized objectnewFoo{Quantity=newInformation(1.20m,InformationUnit.Exabyte)};
<Fooxmlns="http://schemas.datacontract.org/2004/07/UnitsNet.Tests.Serialization"xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Quantityi:type="a:Information"xmlns:a="http://schemas.datacontract.org/2004/07/UnitsNet"> <a:Value>1.20</a:Value> <a:Unit>Exabyte</a:Unit> </Quantity></Foo>
For JSON, we recommendUnitsNet.Serialization.JsonNet with Json.NET (Newtonsoft) instead.
All quantities and theIQuantity interface have[DataContract] annotations and can be serialized by the built-in JSONDataContractJsonSerializer.
It is not recommended, because the enum value is serialized as integer and this value is not stable.
Schema:
{"__type":"Information:#UnitsNet","Value":1.20,"Unit":4}See
- WIP: Add serialization support for System.Text.Json #905
- Add serialization support for System.Text.Json (Attempt #2) #966
TODO Test and document here.
We strive to maintain backwards compatibility of round-trip serialization within a major version.However, the quantities and units themselves are inherently not stable:
- The base unit of quantities has changed several times in the history, e.g. Kilogram -> Gram.
- The unit enum value is not stable due to code generator sorting units alphabetically.
This is why the full unit name is serialized in Json.NET, so we can avoid ambiguity and be robust to any internal changes of the quantities and units.