質問

I have a simple class like so:

public class MyClass
{
        public string String1;
        public string String2;

        public MyClass()
        {

        }

        public MyClass(string Json)
        {

        }
}

If the class is instantiated without a parameter, it just brings back an empty object.. However, when I pass a string of JSON to the constructor I would like to set all the properties equal to their value in the JSON.

I have done this outside of the class using JSON.NET by Newtonsoft, like this:

string JsonArray = Base64.Decode(HttpContext.Current.Request.QueryString["songinfo"]);
MyClass tmp = JsonConvert.DeserializeObject<MyClass>(JsonArray);
MyClass InstantiatedClass = tmp;

InstantiatedClass is now a fully populated object.. But, I would like to achieve this within the constructor itself, but I can't figure out a way to do it..

I've tried things like setting this = JsonConvert.DeserializeObject<MyClass>(Json), but of course, this is read-only.

I know I could do it by parsing the Json and setting each variable equal to it's appropriate JSON attribute value, but I'd like to do it this way because it's cleaner.

役に立ちましたか?

解決

You can't do it from the constructor. You might consider a factory method within MyClass like so:

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

A constructor doesn't return anything, and as you stated this is read-only. Thus, doing it in the constructor isn't really possible without (as you stated) manually parsing the JSON and initializing the different variables within that instance.

The factory method is probably what you're looking for.

他のヒント

You could do sth like this:

public class MyClass
{
    public string String1;
    public string String2;

    public MyClass()
    {

    }

    public static MyClass Instance(string json)
    {
        return new JsonConvert.DeserializeObject<MyClass>(json);
    }
}

But this is just some kind of a workaround on what you want to achieve. There is in fact no possibility to do this via constructor directly.

public MyClass(string Json)
{
    MyClass tmp = (MyClass) JsonConvert.DeserializeObject<MyClass>(Json);

    this.String1 = tmp.String1;
    this.String2 = tmp.String2;
}

Note, you have access to all private members of the MyClass inside MyClass methods.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top