Bunny83 / SimpleJSON

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

call ToString() method auto append " #29

Closed lyx32 closed 4 years ago

lyx32 commented 4 years ago

Hi Bunny83。 I am coming again。 The same question as before。 But this time I modified the sample code and it works.

sample1

`

    String jsonString = "{\"id\":\"1\",\"name\":\"name-1\"}";
    JSONNode j = JSON.Parse(jsonText);
    String id1 = j["id"];                   // return 1
    String id2 = (String)j["id"];           // return 1
    String id3 = j["id"].ToString();        // return "1"
    String name1 = j["name"];               // return name-1
    String name2 = (String)j["name"];       // return name-1
    String name3 = j["name"].ToString();    // return "name-1"

`

sample2

`

    using (StreamReader sr = new StreamReader("D:\\json.txt"))
    {
        JSONNode j = JSON.Parse(sr.ReadToEnd());
        String id1 = j["id"];                   // return 111
        String id2 = (String)j["id"];           // return 111
        String id3 = j["id"].ToString();        // return "111"
        String name1 = j["name"];               // return json.text.name
        String name2 = (String)j["name"];       // return json.text.name
        String name3 = j["name"].ToString();    // return "json.text.name"
    }

`

file "json.txt" content {"id":"111","name":"json.text.name"}

Bunny83 commented 4 years ago

Well as I said the last time this is not an issue and is the expected behaviour.

Casting a JSONNode to string implicitly or explicitly will try to get the string content of that node. In case of a JSONString it will just return the string itself.

ToString on the other hand will convert the JSONNode back into JSON. So a JSONString of course need to be quoted. Your proposed changes in your other issue would completely break the serialization into JSON.

There are 3 ways how to read the content as a string:


string name1 = j["name"];  // implicit cast
string name2 = (string)j["name"];  // explicit cast
string name3 = j["name"].Value;  // the Value property

As said ToString will convert the node into json:

string json1 = j["name"].ToString();  // will return the JSONNode name serialized to inline JSON
string json2 = j["name"].ToString(3);  // will return the JSONNode name serialized to formatted JSON
lyx32 commented 4 years ago

Oh, okay, I see what you mean. But since you don't think what I said is a problem, So sorry to bother you. Thank you for your answer. I am translating English using translation software. If anything offends, please forgive me.