Marshall Deering Marshall Deering - 1 year ago 80
C# Question

Why is all of this needed for JSON?

I am learning JSON and I have gotten it to work, but I am wanting to know WHY it works and how it works. I am confused as to why some lines are needed and what they do.

Below is my main cs and my

class: I am under the impression that I am making
equal to the content of JSON.json. If that is the case, why can I not just
Writeline JSONstring
and add
there to separate lines?

From what I gather is that
which is equal to the deserialized JSON. I am not exactly sure why the other code is needed.

// Make JSONstring = to the text in JSON.json
String JSONstring = File.ReadAllText("JSON.json");

JavaScriptSerializer ser = new JavaScriptSerializer();
Person p1 = ser.Deserialize<Person>(JSONstring);

class Person
public string name { get; set; }
public int age { get; set; }

public override string ToString()
return string.Format("Name: {0} \nAge: {1}", name, age);

Answer Source

is not displaying JSON. In effect, it calls the ToString() method on p1:

return string.Format("Name: {0} \nAge: {1}", name, age);

and outputs the result to the console. ToString() can return anything you wish.

As to your original question, the purpose of such a serialization is to save the state of an object to a text-based, human-readable form, and then create an object later having that same state. The ToString method doesn't have much to do with that, other than to give you a convenient way of viewing the state.

The "state" is the value of the member variables nameand age, in your example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download