Bunny83 / SimpleJSON

A simple JSON parser in C#
MIT License
735 stars 294 forks source link

.ToString() for JSONNode string keys returns quoted strings #47

Open flberger-work opened 2 years ago

flberger-work commented 2 years ago

When doing node["somekey"].ToString() on a JSONNode where the value is already a string, the string is returned wrapped into double quotes, so .ToString() currently returns a literal "abc" instead of an expected abc string.

That happens in WriteToStringBuilder() of class JSONString, that explicitly does

aSB.Append('\"').Append(Escape(m_Data)).Append('\"');

Is there a rationale for this? I was using .ToString() as an easy way to make sure to get a string representation, no matter what the actualy type may have been. However, the unexpected quotes lead to errors e.g. in comparing with expected values, or further parsing the string, so I find myself .Trim()ing them away.

Actual behaviour: string values are returned wrapped in quotes.

Expected behaviour: the string should be returned without quotes.

Thanks for considering.

Bunny83 commented 2 years ago

Well, yes, it's an unfortunate side effect. However the ToString method is actually used to return the json representation of a node. So the result should be quoted, so that's actually correct. The ToString method in C# in general should return a string representation of the object. In case of the JSONNode class that representation is the json representation.

If you want to get the string value there are currently two ways:

string str = node; or string str = (string)node

The other way is to use the "Value" property

string str = node.Value;

Again, a JSONNode represents a json string and not a string.