angularsen / UnitsNet

Makes life working with units of measurement just a little bit better.
https://www.nuget.org/packages/UnitsNet/
MIT No Attribution
2.18k stars 379 forks source link

UnitsNetJsonConverter is obsolete - How to use the new implementation? #826

Closed MadsFoged closed 4 years ago

MadsFoged commented 4 years ago

The way I did it before was:

        public string SaveAsJSON()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented, ReturnJSONSettings());
        }

        public static MyClass LoadFromJSON(string json)
        {           
            return JsonConvert.DeserializeObject<MyClass>(json, ReturnJSONSettings());
        }

        public static JsonSerializerSettings ReturnJSONSettings()
        {
            //Setting for both UnitsNet and PreserveReferences
            var JsonSettings = new JsonSerializerSettings
            {
                PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                TypeNameHandling = TypeNameHandling.All,
                ContractResolver = new PrivateSetterAndCtorContractResolver()
            };            
            JsonSettings.Converters.Add(new UnitsNetJsonConverter());           

            return JsonSettings;
        }

Can you help me explain how to do it the new way?

angularsen commented 4 years ago

Instead of

JsonSettings.Converters.Add(new UnitsNetJsonConverter());

try

JsonSettings.Converters.Add(new UnitsNetIQuantityJsonConverter());

There is also UnitsNetIComparableJsonConverter() if you need to support deserializing props/fields of type IComparable.

See: https://github.com/angularsen/UnitsNet/blob/3221861cd4703fd09b617b4e1831a1e5c27efde5/UnitsNet.Serialization.JsonNet.Tests/Infrastructure/UnitsNetJsonBaseTest.cs#L12-L17

angularsen commented 4 years ago

I updated the readme with an example: https://github.com/angularsen/UnitsNet/blob/master/README.md#serialization