Selen
Selen

Reputation: 210

How can I serialize an int value with json without class object?

I want to serialize an integer into a file as a json object. Normally, I can serialize with object (other class object) like this;

void Serialize()
        {
            string json = JsonConvert.SerializeObject(obj, Formatting.Indented );
            File.WriteAllText(path_combined, json);

        }

obj is the communication bridge with other class, however I have integers in this class, so I have to serialize without object. I looked other questions, they all use objects. I couldn't find a way to convert an integer to json string(or whatever it is) to serialize. Can you please help?

Upvotes: 2

Views: 9466

Answers (1)

Alex Sherzhukov
Alex Sherzhukov

Reputation: 253

Any type, including Integer is object in C#. So basically you can serialize integer like you mentioned, e.g.:

int myInt = 10;
string jsonStr = JsonConvert.SerializeObject(myInt); 
// 10
string jsonStr = JsonConvert.SerializeObject(new { myInt }); // new object with int field
//{"myInt":10}

JSON string itself is bunch of key-value pairs (string keys and string / int / array of strings or ints / object values) wrapped into object, but single int it convets to single int string.

So you can not serialize int like { 10 } because this is not valid JSON.

More here: https://www.w3schools.com/js/js_json_intro.asp

Upvotes: 3

Related Questions