-1

Hello i am having a class that is defined in a .Net Standard assembly. Now i have a reference to that assembly from my .Net Core project.

When i try to deserialize the class in my .Net Core my class fields are default.

By default i mean value types get all inner values default and class fields are null. In my example if Val is an int it would have its value 0 after deserialization whereas would it have been a class it would be null.

.NET Standard class

public  class Matrix
{
    public int Val { get; set; }


    public Matrix(int set) //value is default
    {
        this.Val = set;
    }
}

.NET Core

static void Main(string[] args)
{

    Matrix matr = new Matrix(3);


    var str=JsonConvert.SerializeObject(matr);
    var bytes=Encoding.Utf8.GetBytes(str);


    var str = Encoding.UTF8.GetString(bytes); //string looks ok !


    var deser = JsonConvert.DeserializeObject<Matrix>(str);

}

Please note that my class uses a parameter in the constructor.Could this be the problem ? If my parameter constructor is indeed the problem ...how do you manage to serialize an object that needs to perform some logic in its constructor via his parameters ?

Bercovici Adrian
  • 8,794
  • 17
  • 73
  • 152
  • 1
    This code has several invalid and compiles time issues. For instance, `DeserializeObject` accepts a string. To make sure others can replicate your issue, can you paste the exact content from your editor/IDE? If you need to change something to hide content, make sure your simplified code compiles and replicates the issue. – Neville Nazerane Feb 16 '19 at 22:47
  • What do you mean exactly when you say *my class fields are default*? Do you mean that `Assert(deser.Val == matr.Val);` would fail, because `deser.Val` (which is actually a property, not a field) is zero after deserialization? Or do you mean something else? A [mcve] including an `Assert` statement that fails but should succeed would be ideal, and maximize the chance we can help you. – dbc Feb 16 '19 at 22:54
  • 1
    But possibly related: [Usage of non-default constructor breaks order of deserialization in Json.net](https://stackoverflow.com/q/36866131/3744182) and [Json.net `JsonConstructor` constructor parameter names](https://stackoverflow.com/q/43032552/3744182) – dbc Feb 16 '19 at 22:56
  • I am sorry that was a typo.I edited my post. – Bercovici Adrian Feb 17 '19 at 05:00

1 Answers1

1

Code which you provided works good. After deserialization in deser.Val you will see 3. But if you will change public int Val { get; private set; } or public int Val { get; } you will have a default value. For reference type it will be NULL for value type it depends.

Maybe you can provide more information and screenshot of problem?

Nick Sinitsin
  • 247
  • 1
  • 4