How to remove DataContractSerializer verbosity - c#

We are attempting to serialize an object tree. And while we have been successful. I was hoping to find a way to simplify down the generated xml.
The objects look something like the following:
public class RuleSet<T>
{
public IEnumerable<IState<T>> States { get; set; }
public IEnumerable<ICondition<T>> Conditions { get; set; }
}
public class State<T> : IState<T>
{
public string Id { get; set; }
public List<ITransition<T>> Transitions { get; set; }
}
public class Transition<T> : ITransition<T>
{
public ICondition<T> Condition { get; set; }
public IState<T> Next { get; set; }
}
public class Condition<T> : ICondition<T>
{
public string Id { get; set; }
public string Name { get; set; }
}
We are using a really simple serialization code at the moment:
public void blah()
{
var condition1 = new Condition<object>() {
Id = "C1", AttributeName = "Foo", ExpectedValue = "Bar"
};
var condition2 = new Condition<object>() {
Id = "C2", AttributeName = "Bar", ExpectedValue = "Foo"
};
var state1Transitions = new List<ITransition<object>>();
var state2Transitions = new List<ITransition<object>>();
var state3Transitions = new List<ITransition<object>>();
var state = new State<object> {
Id = "S1", Transitions = state1Transitions
};
var state2 = new State<object> {
Id = "S2", Transitions = state2Transitions
};
var state3 = new State<object> {
Id = "S3", Transitions = state3Transitions
};
state1Transitions.Add(new Transition<object> {
Condition = condition1, Next = state2
});
state1Transitions.Add(new Transition<object> {
Condition = condition2, Next = state3
});
state2Transitions.Add(new Transition<object> {
Condition = condition2, Next = state3
});
var ruleSet = new RuleSet<object> {
States = new List<IState<object>> {state, state2, state3},
Conditions = new List<ICondition<object>>{condition1, condition2}
};
var stream1 = new MemoryStream();
var serializer = new DataContractSerializer(typeof(RuleSet<object>),
new List<Type> {
typeof(State<object>),
typeof(Transition<object>),
typeof(AttributeEqualTo<object>)
});
serializer.WriteObject(stream1, ruleSet);
stream1.Position = 0;
var xml = new StreamReader(stream1).ReadToEnd();
Console.WriteLine(xml);
}
When the XML is generated the output for each level is complete instead of only containing the reference to the object. Basically for each Transition<T> we get a complete object definition for each state and condition even if they are defined elsewhere.
Is there a way to get those to simply be references?

It all comes down to how you create your DataContractSerializer.
You'll want to call the overload of the constructor that allows you to indicate that you will preserve object references, with the following signature:
public DataContractSerializer(
Type type,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
IDataContractSurrogate dataContractSurrogate
)
You can pass default values for most of the parameters. In your case, the call to the DataContractSerializer constructor will look like this:
var serializer = new DataContractSerializer(typeof(RuleSet<object>),
new [] {
typeof(State<object>),
typeof(Transition<object>),
typeof(AttributeEqualTo<object>)
},
Int32.MaxValue,
false,
/* This is the important flag to set. */
true,
null
);
Note, from the preserveObjectReferences parameter documentation, it uses non-standard XML (emphasis mine):
preserveObjectReferences
Type: System.Boolean
true to use non-standard XML constructs to preserve object reference data; otherwise, false.
If you need other code outside of .NET to interpret this, then untangling the references might prove to be difficult (but shouldn't be impossible).
However, it prevents the object graph from replicating itself over and reduce the size of your XML (possibly considerably, given how deep your references go).

Related

Deserialize JSON into dynamic class

I need to deserialize a JSON string into a type which is not know at compile time. There are several classes that it can be deserialized into. The name of the class is provided as input into the application and based on that I want to instantiate the class (already done this through reflection):
var type = Type.GetType(className);
var myClassInstance = (IParser)Activator.CreateInstance(type);
...and then use its type as the generic type parameter for JsonConvert.DeserializeObject<typeof(myClassInstance).Name>(jsonString) but that doesn't work.
How can I provide the class to DeserializeObject<>() dynamically?
Instead of using an generic method overload like JsonConvert.DeserializeObject<T>(String) and having to resort to reflection as some comments state, you could simply use the non generic counterpart JsonConvert.DeserializeObject(String, Type), which just takes in a Type instance like you already have!
Implementation
Initialization
var class1s = new Class1() {
ID = 1, Name = "Test", Comment = "This Code is Tested!."
};
var class2s = new Class2() {
xVal1 = 1, XVal2 = 5, xval3 = 10
};
var JSON1 = Newtonsoft.Json.JsonConvert.SerializeObject(class1s);
var JSON2 = Newtonsoft.Json.JsonConvert.SerializeObject(class2s);
Calling Functions
var classname1 = typeof(Class1).FullName;
var type1 = Type.GetType(classname1);
var classname2 = typeof(Class2).FullName;
var type2 = Type.GetType(classname2);
var c = LocalConverter(JSON1, type1);
var c2 = LocalConverter(JSON2, type2);
Class Models
public class Class1 {
public int ID {
get;
set;
}
public string Name {
get;
set;
}
public string Comment {
get;
set;
}
}
public class Class2 {
public int xVal1 {
get;
set;
}
public int XVal2 {
get;
set;
}
public int xval3 {
get;
set;
}
}
Required Method
private object LocalConverter(string o, Type xtype) {
return Newtonsoft.Json.JsonConvert.DeserializeObject(o, xtype);
}

MongoDB C# Driver: flatten object

Imagine I have a class structure like this
class Aggregate
{
string Id {get;set;}
Parameters Parameters {get;set;}
}
class Parameters
{
List<string> Values {get;set;}
// logic based on Values
}
Now I want mongo to store it like this
{
"_id": "...",
"parameters": ["param A", "param B"]
}
How do I configure it using BsonClassMap.RegisterClassMap?
I'm ignoring the fact that the members of your class are private at the moment, as that would mean you couldn't read anything from the class. So let's just make them public
class Aggregate
{
public string Id { get; set; }
public Parameters Parameters { get; set; }
}
class Parameters
{
public List<string> Values { get; set; }
}
So now we'll need a custom serializer to deal with flattering the object and then also reading back the flattened document.
Below is just a noddy example that delegate serializing Parameters to the BsonArraySerializer.
public class ParametersSerializer : IBsonSerializer
{
private readonly BsonArraySerializer _bsonArraySerializer;
public ParametersSerializer()
{
_bsonArraySerializer = new BsonArraySerializer();
}
public object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var bsonArray = _bsonArraySerializer.Deserialize(context, args);
var netList = BsonTypeMapper.MapToDotNetValue(bsonArray, new BsonTypeMapperOptions()
{
MapBsonArrayTo = typeof(List<string>)
}) as List<string>;
return new Parameters
{
Values = netList
};
}
public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
{
var typed = (Parameters) value;
var bsonArray = new BsonArray(typed.Values);
_bsonArraySerializer.Serialize(context, args, bsonArray);
}
public Type ValueType { get; } = typeof(Parameters);
}
Now we've got this we can just add an attribute to our class to tell Mongo driver to use it.
class Aggregate
{
public string Id { get; set; }
[BsonSerializer(typeof(ParametersSerializer))]
public Parameters Parameters { get; set; }
}
Now when we write and read documents to mongo:
var pack = new ConventionPack();
pack.Add(new CamelCaseElementNameConvention());
ConventionRegistry.Register(
"My Custom Conventions",
pack,
t => t == typeof(Aggregate) || t == typeof(Parameters));
var client = new MongoClient();
var database = client.GetDatabase("test");
var collection = database.GetCollection<Aggregate>("test");
await database.DropCollectionAsync(collection.CollectionNamespace.CollectionName);
await collection.InsertOneAsync(new Aggregate{Id = "...", Parameters = new Parameters{Values = {"1", "2"}}});
var all = await (await collection.FindAsync(Builders<Aggregate>.Filter.Empty)).ToListAsync();
we'll get the following save in MongoDB collection:
> db.test.find()
{ "_id" : "...", "parameters" : [ "1", "2" ] }
Also notice we're using a custom convention of camel case to deal with creating camel case properties too.

Deserialising XML with different element name in c#

XML:
<?xml version="1.0" encoding="UTF-8"?>
<Images>
<I0>
<Path>123.com</Path>
<I0>
<I1>
<Path>123.com</Path>
<I1>
<I2>
<Path>123.com</Path>
<I2>
</Images>
Can serializer.Deserialize() be used to get tags with different names into a collection?
currently, in my object I have:
C#:
public class rootObject
{
[XmlElement(ElementName = "I0")]
public I0 I0 { get; set; }
[XmlElement(ElementName = "I1")]
public I1 I1 { get; set; }
[XmlElement(ElementName = "I2")]
public I2 I2 { get; set; }
}
But I would like to have (Because Images can have more or fewer elements):
public class rootObject
{
public List<I> Is { get; set; }
}
You can do what you are suggesting you just merely need to pass in the type argument in your class doing the generic. The key point to remember when you do a deserialization routine is that the routine needs to know the sub reference. So if I was to say string.Deserialize it would bomb. It would need to know a reference string.Deserialize> where Sub could be the class object that may change.
Say I have a base class and I want 'T' to be a type I can change for extensible abilities later.
[Serializable]
public class Test<T> where T : class
{
public Test() { }
public int TestId { get; set; }
public string Name { get; set; }
public List<T> Shipments { get; set; }
}
I want to test this with two classes I just make up that have different properties slightly
[Serializable]
public class Sub1
{
public int Id { get; set; }
public string Desc { get; set; }
}
[Serializable]
public class Sub2
{
public int IdWhatever { get; set; }
public string DescWhatever { get; set; }
}
Now let's do a main program and test serialization.
class Program
{
static void Main(string[] args)
{
var serializeTest = new Test<Sub1> { TestId = 1, Name = "Test", Shipments = new List<Sub1> { new Sub1 { Id = 1, Desc = "Test" }, new Sub1 { Id = 2, Desc = "Test2" } } };
var serializeTest2 = new Test<Sub2> { TestId = 1, Name = "Test", Shipments = new List<Sub2> { new Sub2 { IdWhatever = 1, DescWhatever = "Test" }, new Sub2 { IdWhatever = 2, DescWhatever = "Test2" } } };
var serialized = serializeTest.SerializeToXml();
var serialized2 = serializeTest2.SerializeToXml();
var deserialized = serialized.DeserializeXml<Test<Sub1>>();
var deserialized2 = serialized2.DeserializeXml<Test<Sub2>>();
Console.WriteLine(serialized);
Console.WriteLine();
Console.WriteLine(serialized2);
Console.ReadLine();
}
}
And my Serialize and DeSerialize extension methods:
public static string SerializeToXml<T>(this T valueToSerialize, string namespaceUsed = null)
{
var ns = new XmlSerializerNamespaces(new XmlQualifiedName[] { new XmlQualifiedName(string.Empty, (namespaceUsed != null) ? namespaceUsed : string.Empty) });
using (var sw = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sw, new XmlWriterSettings { OmitXmlDeclaration = true }))
{
dynamic xmler = new XmlSerializer(typeof(T));
xmler.Serialize(writer, valueToSerialize, ns);
}
return sw.ToString();
}
}
public static T DeserializeXml<T>(this string xmlToDeserialize)
{
dynamic serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(xmlToDeserialize))
{
return (T)serializer.Deserialize(reader);
}
}
You don't need to specify the XmlElement name when the properties match the XML. A few solutions, some kinda hacky :).
HACKY: use regex string replace to replace <I#> and </I#> to
just <I> and </I>
SOMEWHAT HACKY: This might work for you:
How to deserialize an XML array containing multiple types of elements in C#,
but you'd have to add an attribute for i0, i1 ... i100, etc.
BEST: Is that your entire XML? I'd honestly just use LINQToXml and
do a Descendants("Path") and get an array of strings back with 1 line of code. Serialization is not really the best solution for this.

Nested Json array in MVC Controller

Pretty silly question to ask. but could not figure it out .
In a C# MVC Controller action , I need to model a Json Array for testing purposes.
But this shows me compilation errors instead of being a valid Json:
var result = {
"controllerId": "controller1",
"controllerName": "ControllerOne"
};
But this is perfectly valid :
var scheduleResult = new[]
{
new { scheduleId = "schedule1",scheduleName = "scheduleOne"},
new { scheduleId = "schedule2",scheduleName = "scheduleTwo"}
};
Why so ?
Also how to write a nested Json array :
I tried :
var scheduleResult = new[]
{
new { scheduleId = "schedule1",scheduleName = "scheduleOne",new[]{ new {doorId="Door1",doorName="DoorOne"}, new { doorId = "Door2", doorName = "DoorTwo" } } },
new { scheduleId = "schedule2",scheduleName = "scheduleTwo"}
};
But it shows errors in syntax. What to do ?
I Need to have nested array within each element of that array .
Thanks in advance.
Well, C# does not support the way you wrote. You can't just type in JSON in C# and expect it to work unfortunately. You can try like that with anonymous type:
var result = new
{
controllerId = "controller1",
controllerName = "ControllerOne",
myArray = new []
{
"a",
"b"
}
};
This is converted to JSON no problem if you return it as a result of API call.
The nested arrays you are talking about don't work because you need to give them a name, you can't have array property without a name. See example above.
Why don't you use Dictionary<TKey, TValue> with Newtonsoft.Json?
Simple json:
IDictionary<string, string> obj = new Dictionary<string, string>();
obj.Add("controllerId", "controller1");
obj.Add("controllerName", "ControllerOne");
// {"controllerId":"controller1","controllerName":"ControllerOne"}
string json = JsonConvert.SerializeObject(obj);
Nested json:
IList<string> obj = new List<string>();
IDictionary<string, string> first = new Dictionary<string, string>();
first.Add("scheduleId ", "schedule1");
first.Add("scheduleName", "scheduleOne");
IDictionary<string, string> second = new Dictionary<string, string>();
second.Add("scheduleId ", "schedule2");
second.Add("scheduleName", "scheduleTwo");
string first_json = JsonConvert.SerializeObject(first);
string second_json = JsonConvert.SerializeObject(second);
obj.Add(first_json);
obj.Add(second_json);
// ["{\"scheduleId \":\"schedule1\",\"scheduleName\":\"scheduleOne\"}","{\"scheduleId \":\"schedule2\",\"scheduleName\":\"scheduleTwo\"}"]
string json = JsonConvert.SerializeObject(obj);
Here first of all we should create model class with the same pattern of our return type
public class ScheduleModel
{
public List<Schedule> ScheduleList { get; set; }
}
public class Schedule
{
public int ScheduleId { get; set; }
public string ScheduleName { get; set; }
public List<Door> DoorList { get; set; }
}
public class Door
{
public int DoorId { get; set; }
public string DoorName { get; set; }
}
Now at the controller Action create the test data
List<Door> doorList = new List<Door>();
doorList.Add(new Door{DoorId = "Door1",DoorName = "DoorOne"});
doorList.Add(new Door{DoorId = "Door2",DoorName = "DoorTwo"});
List<Schedule> scheduleList = new List<Schedule>();
scheduleList.Add(new Schedule{
ScheduleId = "schedule1",
ScheduleName = "scheduleOne",
DoorList = doorList
});
scheduleList.Add(new Schedule
{
ScheduleId = "schedule2",
ScheduleName = "scheduleTwo",
});
return Json(scheduleList, JsonRequestBehavior.AllowGet);
If this answer benefits you please mark as an answer.

Serialization Fail on list of lists using DataContractSerializer

I have some class that has a property of type List<object> I need to serialize that class to XML file using DataContractSerializer.
The serialization fails on ArgumentException when the object is a List<T>/IEnumerator<T>exception message:
Invalid name character in
'System.Collections.Generic.List`1[[MyProj.Result, MyProj,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'.
Here is the code sample that fails
The Class that takes the List<object>
[DataContract(IsReference = true)]
public class RecoveryMethodData
{
[DataMember]
public List<object> Parameters { get; set; }
public RecoveryMethodData()
{
Parameters = new List<object>();
}
public static void SerializeToFile(RecoveryMethodData recoveryMethodData, string fileName)
{
var encoding = Encoding.UTF8;
using (var fileWriter = new XmlTextWriter(fileName, encoding))
{
fileWriter.Formatting = Formatting.Indented;
// use SharedTypeResolver for deserializing assistance.
var serializer = new DataContractSerializer(typeof(RecoveryMethodData), null, int.MaxValue, false, true, null, new SharedTypeResolver());
serializer.WriteObject(fileWriter, recoveryMethodData);
}
}
}
Here is the usage:
private void TestSerialization()
{
var methodData = new RecoveryMethodData();
var result = new Result() {Message = "wow", Pass = true, FileName = "somefile "};
methodData.Parameters.Add(result);
methodData.Parameters.Add(true);
var list1 = new List<Result>();
list1.Add(new Result(){FileName = "in list1", Message = "in l 1"});
list1.Add(new Result(){FileName = "in list2", Message = "in l 2"});
methodData.Parameters.Add(list1);
RecoveryMethodData.SerializeToFile(methodData,#"C:\serialization_result.xml");
}
public class Result
{
public string Message { get; set; }
public string FileName { get; set; }
}
If I do not add list1 into the methodData.Parameters there is no problem serializing the methodDatad object.
One big limitation is that I can't know in advance which kind of objects will be added to the Parameters property (that is why it is a list of objects)
In order to DataContractSerializer to serialize an object, it shall know the types of all datamembers. In your case, you do not define a specific type but an object type. Try changing the definition of
public List<object> Parameters { get; set; }
to something like:
public List<IMyObject> Parameters { get; set; }
Note that, all of your objects which you are trying to add to the parameters list shall inherit IMyObject interface.
Update: I refactored your code up to some point (still in a bad shape) and it seems working, please have a try;
public class Tester
{
public Tester()
{
this.TestSerialization();
}
public void SerializeToFile(RecoveryMethodData recoveryMetaData,string fileName)
{
var encoding = Encoding.UTF8;
using (var fileWriter = new XmlTextWriter(fileName, encoding))
{
fileWriter.Formatting = Formatting.Indented;
// use SharedTypeResolver for deserializing assistance.
var serializer = new DataContractSerializer(typeof(RecoveryMethodData),new List<Type>(){typeof(bool),typeof(Result),typeof(List<Result>)});
serializer.WriteObject(fileWriter,recoveryMetaData);
}
}
private void TestSerialization()
{
var methodData = new RecoveryMethodData();
var result = new Result() { Message = "wow", Pass = true, FileName = "somefile " };
methodData.Add(result);
methodData.Add(true);
var list1 = new List<Result>();
list1.Add(new Result() { FileName = "in list1", Message = "in l 1" });
list1.Add(new Result() { FileName = "in list2", Message = "in l 2" });
methodData.Add(list1);
SerializeToFile(methodData, #"C:\serialization_result.xml");
}
}
public class Result
{
public string Message { get; set; }
public string FileName { get; set; }
public bool Pass { get; set; }
}
public class RecoveryMethodData : List<object>
{
}

Categories

Resources