Kenny
Kenny

Reputation: 2176

Deserialize into same object using JsonConvert (c#)

I have a method in my class that uses an API to get data. Next I use JsonConvert.DeserializeObject to create another instance of the same class, then I copy the values to the object I'm in, which is where I wanted the values in the first place. Although this works just fine, it seems like there must be a better way to do this. (I know it could be further refactored for SRP. I'm just trying to find a more efficient way to get the values into the members.)

Can anyone show me a better way?

         public class MyModel
         {
            public string Description { get; set; }
            public string Last_Name { get; set; }
            public string Nickname { get; set; }


            public void Load()
            {
                var results = {code that gets stuff}
                MyModel item = JsonConvert.DeserializeObject<MyModel>(results.ToString());

                this.Description = item.Description;
                this.Last_Name = item.Last_Name;
                this.Nickname = item.Nickname;
            }
            .
            .
            .

         }

Upvotes: 0

Views: 225

Answers (1)

Filip Cordas
Filip Cordas

Reputation: 2561

Do you want this

class A
        {
            public int Id { get; set; }

            public string Value { get; set; }

            public void Load()
            {
                var json = @"{Id:1,Value:""Value""}";
                JsonConvert.PopulateObject(json, this);
            }
        }

Upvotes: 1

Related Questions