Serialize objest as string value (as if calling ToString() on it) with c# driver

73 views
Skip to first unread message

Sharas gpavarde

unread,
Jun 6, 2014, 3:56:13 PM6/6/14
to mongod...@googlegroups.com
Hi,

I have a datastructure in c#
public class ResourceSpec
{
       
public string TypeName
       
{
           
get;
           
private set;
       
}

       
public HashSet<ResourceProperty> Properties
       
{
           
get;
           
private set;
       
}

}



public class ResourceProperty
{
     
public string Val
     
{
         
get;
         
private set;
     
}

}

I want it to be serialized into:

{TypeName: 'blabla', Properties: ['value1', 'value2', 'value3' ]}

Instead of 
 
{TypeName: 'blabla', Properties: [{Val: 'value1'}, {Val: ' value2'}, {Val: ' value3'}] }

How can I do that?

William Berkeley

unread,
Jun 30, 2014, 1:44:13 PM6/30/14
to mongod...@googlegroups.com

Hey Sharas. Are you still having troubles with this?  If you want to change how an object is serialized into a string, override the ToString() method to produce a string in the desired format.


-Will

Sharas gpavarde

unread,
Jun 30, 2014, 4:49:53 PM6/30/14
to mongod...@googlegroups.com
Hi,

Thats what I did, but that object is held by parent object that I am serializing. And I have no easy way to tell serializer "When you serialize that child object call ToString on it".


--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: http://www.mongodb.org/about/support/.
---
You received this message because you are subscribed to a topic in the Google Groups "mongodb-user" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/mongodb-user/pVsS6kLdoZI/unsubscribe.
To unsubscribe from this group and all its topics, send an email to mongodb-user...@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at http://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/f1d9c791-41ca-420b-ba44-1bdef7de1eb6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

William Berkeley

unread,
Jul 7, 2014, 11:03:47 AM7/7/14
to mongod...@googlegroups.com
Hey Sharas. Based on the code you've given us, you could change

public HashSet<ResourceProperty> Properties { get; private set; }

to

public HashSet<string> Properties { get; private set; }

and get the desired serialization. However, if you want a more complicated structure for ResourceProperty than just a string value that will also serialize correctly when embedded in the parent document, look at implementing IBsonSerializer for ResourceProperty. You'll find the interface in the C# API docs under the MongoDB.Bson.Serialization Namespace.

-Will
Reply all
Reply to author
Forward
0 new messages