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
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.
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}'.
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
The standard way to do this kind of thing is to provide an insertion operator so that an object can be inserted into a stream -- which may be any kind of stream, such as a stringstream.
If you wish, you can also provide a method that converts to a string (useful for your insertion operator), and, if you find the conversion acceptable, you can provide a 'to string' operator.
Here's my standard 'point' class example:
template <typename T>
struct point
{
T x;
T y;
point(): x(), y() { }
point( T x, T y ): x(x), y(y) { }
};
template <typename T>
std::ostream& operator << ( std::ostream& outs, const point <T> & p )
{
return outs << "(" << p.x << "," << p.y << ")";
}
I also tend to keep a handy function around to convert things to strings:
template <typename T>
std::string to_string( const T& value )
{
std::ostringstream ss;
ss << value;
return ss.str();
}
Now I can use it easily:
int main()
{
point p (2,-7);
std::cout << "I have a point at " << p << ".\n";
my_fn_which_takes_a_string( to_string(p) );
You'll find that the Boost Lexical Cast Library is also designed for this kind of thing.
Hope this helps.
The C++ standard does not prescribe a way to do this but it looks like there is a proposal which may introduce such an option Generic to_string/to_wstring functions which says in the motivation section which also highlights the current common practices being taken(which I demonstrate below):
For a long time C++ programmers have been looking for an easy way to convert an object into its string representation. A typical answer to this problem was to create a local ostringstream, insert the object into the stream, and then obtain the resulting string with the str member function. This solution is simple, safe, flexible and extensible, though definitely too verbose for something that rather ought to be a single function call. C++11 provided (a partial) solution in the form of a set of overloaded to_string/to_wstring functions. Unfortunately, these are limited only to the built-in numeric types. Non-standard solutions exist too – most notably boost::lexical_cast, which offers two-way conversion of objects and strings, but lacks any formatting control.
This paper proposes a solution that:
- generalizes the existing to_string/to_wstring functions for any type that provides a stream output operator and for any basic_string specialisation,
- remains consistent and mostly compatible with these functions,
- provides extra formatting and concatenation capabilities,
- is conceptually simple by building upon the familiar ostringstream solution.
There are two trip reports STL's and Herb Sutter's and I don't see this paper mentioned in either. So hopefully this will be covered in the post-Kona mailing when it comes out.
The first method they mentioned in the proposal would look something like the example in this answer:
class A {
public:
int i;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.i << ")";
}
combined with the something similar to the example from here:
template <typename T>
std::string to_string(const T& value) {
std::ostringstream os;
os << value;
return os.str();
}
We can find a boost::lexical_cast example in the question Enabling Classes for Use with boost::lexical_cast.
You are returning a string that just says the phrase _name + _number + _date + _salary.
What you likely wanted to do is build a string using those fields. If you wanted them all mushed together Concat would work, but it would be highly un-readable
public override string ToString()
{
return String.Concat(_name, _number, _date, _salary);
}
However what would be better is to use Format and include labels with the values
public override string ToString()
{
return String.Format("Name:{0}, Number:{1}, Date:{2}, Salary:{3}",_name, _number, _date, _salary);
}
If you are using C# 6 or newer you can use the following cleaner format
public override string ToString()
{
return $"Name:{_name}, Number:{_number}, Date:{_date}, Salary:{_salary}";
}
Which is the exact same logic as the previous String.Format version.
The reason people override the ToString() method is to have a default string representation of your object, usually for display to the user or in a log or console, like this:
Console.WriteLine(yourClassObject);
If you do not override the ToString(), then its default implementation is to return the fully qualified name of your object, like this:
YourNamespace.YourClassName
By changing the inherited implementation (from System.Object), then you can make a nicer (read: prettier) representation, like this:
public override string ToString()
{
return String.Format("This instance of my object has the following: Name = {0}, Number = {1}, Date = {2}, Salary = ${3}", _name, _number, _date, _salary);
}