No need to reinvent the wheel. Use Json.Net
string s = JsonConvert.SerializeObject(yourObject);
That is all.
You can also use JavaScriptSerializer
string s = new JavaScriptSerializer().Serialize(yourObject);
Answer from I4V on Stack OverflowNo need to reinvent the wheel. Use Json.Net
string s = JsonConvert.SerializeObject(yourObject);
That is all.
You can also use JavaScriptSerializer
string s = new JavaScriptSerializer().Serialize(yourObject);
string jsonString = JsonSerializer.Serialize(yourObject);
Its the recommended way these days with System.Text.Json; Read more here.
Videos
The two are intended for different purposes. The ToString method of any object is supposed to return a string representation of that object. Casting is quite different, and the 'as' key word performs a conditional cast, as has been said. The 'as' key word basically says "get me a reference of this type to that object if that object is this type" while ToString says "get me a string representation of that object". The result may be the same in some cases but the two should never be considered interchangeable because, as I said, they exist for different purposes. If your intention is to cast then you should always use a cast, NOT ToString.
from http://www.codeguru.com/forum/showthread.php?t=443873
see also http://bytes.com/groups/net-c/225365-tostring-string-cast
If you know it is a String then by all means cast it to a String. Casting your object is going to be faster than calling a virtual method.
Edit: Here are the results of some benchmarking:
============ Casting vs. virtual method ============
cast 29.884 1.00
tos 33.734 1.13
I used Jon Skeet's BenchmarkHelper like this:
using System;
using BenchmarkHelper;
class Program
{
static void Main()
{
Object input = "Foo";
String output = "Foo";
var results
= TestSuite.Create("Casting vs. virtual method", input, output)
.Add(cast)
.Add(tos)
.RunTests()
.ScaleByBest(ScalingMode.VaryDuration);
results.Display(ResultColumns.NameAndDuration | ResultColumns.Score,
results.FindBest());
}
static String cast(Object o)
{
return (String)o;
}
static String tos(Object o)
{
return o.ToString();
}
}
So it appears that casting is in fact slightly faster than calling ToString().
Rust's approach: Display and Debug traits
Rust uses the trait system, through the Display and Debug traits, to model types that may be converted to strings, with two possible and well-known uses (user-facing and developer-facing, respectively).
However, it statically ensures that values of a type that doesn't implement the Display trait may not be used to construct a string representation; the same for Debug. Hence, Rust doesn't have a default string representation for user-defined types.
Even though there is not a default string representation, the language offers a macro to derive the Debug implementation using a sensible default that follows the type's definition. However, the Display trait may not be derived, which forces the developer to implement the user-facing string conversion explicitly.
Haskell has a similar mechanism via the Show type class, which may be derived.
Another option is to simply forbid string coercion, as e.g. Python does. This makes it the programmer's responsibility to explicitly convert other values to strings where necessary, but also means there is no uniquely privileged way to convert to a string.
In Python for example, there are the str and repr functions which convert values to strings in different ways (and which can have user-defined behaviour via the __str__ and __repr__ dunder methods), but you can also convert to string through other means, such as by calling some other method defined by the object's class, or using string formatting or f-strings which may offer more options for how the conversion is done, such as f'{x:.02f}'.
s(message) actually calls the constructor of std::string, which constructs a new object of this type from the given character array pointed to by message. s is just an arbitary name given to the string object. std::string is C++'s idiomatic object for working with strings, it is usually preferred over raw C strings.
Consider this simple sample:
// Declare a fresh class
class A {
public:
// a (default) constructor that takes no parameters and sets storedValue to 0.
A() {storedValue=0;}
// and a constructor taking an integer
A(int someValue) {storedValue=someValue;}
// and a public integer member
public:
int storedValue;
};
// now create instances of this class:
A a(5);
// or
A a = A(5);
// or even
A a = 5;
// in all cases, the constructor A::A(int) is called.
// in all three cases, a.storedValue would be 5
// now, the default constructor (with no arguments) is called, thus
// a.storedValue is 0.
A a;
// same here
A a = A();
std::string declares various constructors, including one that accepts a const char* for initialization - the compiler automatically chooses the right constructor depending on the type and number of the arguments, so in your case string::string(const char*) is choosen.
That is actually one of the constructors of std::string.
In C++, you can create objects a few different ways.
std::string s = "Hello"; // implicit constructor using const char *
std::string s = std::string("Hello"); // invoke the const char* constructor of std::string
std::string s("Hello"); // another way to do the stuff above
There are more ways than that, but just to demonstrate how you could create this std::string object.
Hello guys, I would like to know the best way to convert object to string with commas separating the year month & day in format (yyyy,mm,dd) . I am trying to do so for the program to place information into a data file. The conversion follows the code line below. I seek your kind assistance and many thanks.
MyDate MyDate = cannedFood.getexpiryDate(); // to convert object MyDate into string
Hi all. I am trying to code a small scale "game" for an assignment and have gotten a bit stuck. I have created a nested list like a 2d grid with a class, whose elements consist of class objects from another class. this turned out to be rather difficult to decipher as it only returns class.Class object at <address>. I want the program to represent the objects with either the string "O" or ".". I do, however, not have a single clue as to how to do this. I tried writing a magic str() method which did convert them to "O", but then, instead of a 2d grid, it turned into a vertical line of O's. here's the code for that attempt :
def __str__(self) :
tekst = " "
for self._radliste in self._brett :
tekst+= ""
for kololiste in self._radliste :
if str(kololiste) == "." :
tegn = "."
else :
tegn = "O"
tekst += tegn + "\n"
#tekst += "\n" + "\n"
return tekstlater I tried
def __str__(self):
for a in self._brett :
for b in a :
for c in b :
Celle.hentStatusTegn(c)
if c == "." :
tegn = "."
elif c == "O" :
tegn = "O"
return tegnwhich did nothing.
The code for the class I am using will be put down below. these snippets all work.
import random from celle import Celle
class Spillebrett :
def __init__(self, rader, kolonner) :
self._rader = rader
self._kolonner = kolonner
self._brett = []
self._radliste = []
for i in range(self._kolonner) :
kololiste = []
for y in range(self._rader) :
objektet = Celle()
kololiste.append(objektet)
self._radliste.append(kololiste)
for x in self._radliste :
print(x)
gen = 0
self._genererer()
self.tegnBrett(rader)and then the code for creating the board (or so I thought).
def tegnBrett(self, rader) :
self._brett = []
for i in self._radliste :
self._brett.append([])
for j in i :
self._brett.append(self._radliste)
#for i in range(15) :
#print(" ")
return self._brettI am not getting any errors.
sorry for the long post, it's my first time posting here and I hope any experienced programmers can help me out! thank you!