n as
n as

Reputation: 619

C# Constructor from deserialized json?

I have a class which represent a json api. I have created a constructor that is using switched enums to select how the object is to be populated. One is for the minimum equivalent json object. Another is intended populate the properties by reading in from a file. So, I can read the file into a string and deserialize it, but what do I do next to populate the properties?

// this code is in the constructor
string text = System.IO.File.ReadAllText(fileName);
this.???? = JsonConvert.DeserializeObject<MyObject>(text);  // MyObject is the object the constructor is working on

Can I cast the deserialized text into the object's properties?

Sorry for asking something that has probably already been asked, but I don't know if I am even asking the question properly (let alone searching for it). Thanks...

Upvotes: 1

Views: 649

Answers (2)

Dario Griffo
Dario Griffo

Reputation: 4274

As I mentioned in a comment, use a factory instead of the switch in the constructor. If you want to keep it in the constructor use automaper and do this instead

public class MyObject
{
    public MyObject()
    {

    }

    public MyObject(Enum e)
    {
        string text = System.IO.File.ReadAllText(fileName);
        var source = JsonConvert.DeserializeObject<MyObject>(text);            
        Mapper.CreateMap<MyObject, MyObject>();
        Mapper.Map(source, this);
    }

    public string Name { get; set; }

}

Upvotes: 1

Matt Burland
Matt Burland

Reputation: 45135

Not tested, but I think you could do something like this:

public MyObject(MyEnum e)
{
    switch(e) 
    {
        case MyEnum.ValueThatMeansWeDeserializeFromJSON:
            string text = System.IO.File.ReadAllText(fileName);
            var serializer = new JsonSerializer();
            serializer.Populate(new JsonTextReader(new StringReader(text)), this);
            break;
    }
}

Populate will take an existing object and try to deserialize the properties from JSON into that object (as opposed to DeserializeObject which will create a new object.

Upvotes: 1

Related Questions