Reputation: 11
Lets say i have an object with this format:
public class ObjectClassSample
{
public string product { set; get; }
public string Description { set; get; }
public int Price { set; get; }
}
Im trying to same this object inside a string field in a record in my database. is it possible to this without converting this to JSON, as i was thinking what is the best way to save and restore this.
Upvotes: 0
Views: 180
Reputation: 5750
One way or another you have to convert that object to a string, I'm unsure why you don't want to use JSON, but to do it without converting to JSON, you could make your own error prone format.
Here is an example of just converting the object to a string, separating each property by a comma.
Some Extension Methods
public static class ObjectSampleExtensions
{
public static ObjectClassSample ToObjectClassSample(this string s)
{
var parts = s.Split(new [] { ','});
return new ObjectClassSample
{
product = parts[0],
Description = parts[1],
Price = int.Parse(parts[2])
};
}
public static string ConvertToString(this ObjectClassSample objectToConvertToString)
{
const string delimiter = ",";
var sb = new StringBuilder();
sb.Append(objectToConvertToString.product);
sb.Append(delimiter);
sb.Append(objectToConvertToString.Description);
sb.Append(delimiter);
sb.Append(objectToConvertToString.Price);
return sb.ToString();
}
}
Then Usage
void Main()
{
var obj = new ObjectClassSample
{
Description = "this is the description",
Price = 3,
product = "my product"
};
var s = obj.ConvertToString();
//you can now save s to the database
Db.Save(s);
//later on pretend you read 's' back from the database
s = Db.ReadAnItem();
var objectFromDb = s.ToObjectClassSample();
}
So yeah, you can serialize the data anyway you want, but I would use a common format: json, xml, csv, whatever.
I wouldn't recommend using the code above, that was just an example to show you can basically do whatever you want to convert it to a string, so long as you can convert it back. Using a json parser would be much easier though.
An example with ServiceStack.Text would look like this
var objToSerialize = new ObjectClassSample(); //fill this with data
string myObjectAsString = objToSerialize.ToJson();
//reading it back from the database
ObjectClassSample myObj = myObjectAsString.FromJson<ObjectClassSample>();
I'm sure newstonsoft.json is similar.
As you can see...much prettier.
Upvotes: 1