1

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

5
  • This is the constructor for MyObject? Or MyObject is a property in whatever class this constructor is from? You might want to write a custom converter. Commented Jan 15, 2015 at 3:09
  • Yes, this is the constructor for MyObject. Commented Jan 15, 2015 at 3:19
  • Looks fine. You just need to make sure that the property is of type MyObject. Commented Jan 15, 2015 at 3:27
  • There's a JsonSerializer.Populate method that might fit the bill for you, although I might favor using a custom converter derived from JsonConverter. Commented Jan 15, 2015 at 4:30
  • Use a factory instead of the constructor Commented Jan 15, 2015 at 12:32

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.