Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Serializing to JSON, XML and more

Andreas Gullberg Larsen edited this pageJun 10, 2023 ·7 revisions

Serialization

(Recommended) Map to your own custom DTO types

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.

UnitsNet.Serialization.JsonNet with Json.NET (Newtonsoft)

Example

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  }}

SerializingIComparable

If you need to support deserializing into properties/fields of typeIComparable instead of typeIQuantity, then you can add

jsonSerializerSettings.Converters.Add(newUnitsNetIComparableJsonConverter());

DataContractSerializer for XML

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>

DataContractJsonSerializer for JSON (not recommended)

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}

System.Text.Json (not yet implemented)

See

Protobuf and other[DataContract] compatible serializers

TODO Test and document here.

Backwards compatibility

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.

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp