0

How can I fix the typecast error...
I want to create new my object using by JSON..

I attached example code..

 public class Person
 {
     public int age;
     public Person(int _age)
     {
         this.age = _age;
     }
 }

 Dictionary<string, object> dic = new Dictionary<string, object>();
 dic.Add("type", "Person");
 dic.Add("data", new Person(25));

 string json = JsonConvert.SerializeObject(dic);

 dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

 Person p2 = (Person)dic["data"];
 Console.WriteLine(p2);
rene
  • 41,474
  • 78
  • 114
  • 152
J.soo
  • 233
  • 1
  • 3
  • 9
  • in with line you getting error? – Jamaxack Jan 16 '16 at 08:23
  • I believe you don't need to pass "type" key into the dictionary. just create a simple array of persons and serialize and deserialize it. for checking "person' type, you can easily check a type of object by, typeof(), function. In short, dont need to use dictioanary, you can simply use, List persons = new List(). then then add your person objects into it. And last, simply you can deserialize and serialize it. – Hiren Visavadiya Jan 16 '16 at 08:37

1 Answers1

1

You getting dictionary of string,Person and casting to Person, thats why it is throwing an exception.

Try var person = JsonConvert.DeserializeObject<Person>((dic["data"].ToString()));

instead ofPerson p2 = (Person)dic["data"];

And person.age will be 25.

EDIT:

  public MainWindow()
        {
            InitializeComponent();

            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("type", "Person");
            dic.Add("data", new Person(25));

            string json = JsonConvert.SerializeObject(dic);

            dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
            var person = JsonConvert.DeserializeObject<Person>((dic["data"].ToString()));

            Console.WriteLine(person.age);
        }

Hope Helps!

Jamaxack
  • 2,400
  • 2
  • 24
  • 42
  • Nope.. Y.Y Console : 'System.Collections.Generic.Dictionary'2[System.String,System.Object] and saying korean blabla.. I did testing in TCP Socket Programming.... – J.soo Jan 16 '16 at 09:32
  • in My Debug mode.. I could see the dictionary value type that is System.Collections.Generic.KeyValuePair – J.soo Jan 16 '16 at 09:33
  • I want this type parsing : json string : {"protocolType":REQ_CONN,"data":Player Object } .. Player has a some variables.. – J.soo Jan 16 '16 at 09:36
  • Jamaxack !! So So too many much veryvery Thank you.. I'm so very happy.. !!!!!!!!! Thank you ! ! ! ! ! ! ^^ – J.soo Jan 16 '16 at 10:16
  • I got it. I want to be a grateful programmer who helped other people like you ! . and .. study in English first.. Y.Y . Have a good day Jamaxack – J.soo Jan 16 '16 at 10:24