Marshall Deering Marshall Deering - 14 days ago 5
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

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

From what I gather is that
Console.WriteLine(p1);
outputs
p1
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);
Console.WriteLine(p1);
Console.ReadLine();

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
Console.WriteLine(p1)

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.

Comments