Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Create and change class at runtime

Tags:

c#

Assume that I'm receiving endless stream of "anonymous" objects as (JSON/XML/whatever) that are supposed to be of same class, however not all objects contains all fields/properties, ex:

{
 object1 : {field1 : 1, field2: 2},
 object2 : {field1 : 3, field4: 5}
}

As you can see if I use either of objects as template and create a class matching it, the other one won't fit as there's a missing property, in the case of limited objects I can go over them and extract all fields then build a class that fits all and default the missing properties for each object.

However in an "endless" stream it's not possible to do it, so the only approach I found is creating Class1 that fits the first object and create the first object, when going to next object if there's an extra property I add it to Class1 and create the second object of Class1, then go again for each object. When Editing Class1 all objects that were made before the edit must include the new property without having to recreate them.

Any idea how to do this??

Note: I don't want to create a new class every time I find a new field, it'll take much time to recreate all old objects not to mention that number of objects is ever increasing.

like image 496
T.Aoukar Avatar asked Nov 09 '22 07:11

T.Aoukar


1 Answers

Use Json.Net library's JObect class.

1- You can use it with dynamic

string json1 = @"{object1 : {field1 : 1, field2: 2}}";
string json2 = @"{object2 : {field3 : 3, field2: 4}}";

dynamic obj = JObject.Parse(json2);
if (obj.object1 != null) Console.WriteLine(obj.object1.field1);
if (obj.object2 != null) Console.WriteLine(obj.object2.field3);

2- You can use it as dictionary

var jObj = JObject.Parse(json1);
if (jObj["object1"] != null) Console.WriteLine(jObj["object1"]["field1"]);

3- It supports Linq. You can enumerate it easily to get all children/descendants etc.

var rootProperties = jObj.Children().OfType<JProperty>()
                    .Select(p => p.Name).ToArray();
like image 101
Eser Avatar answered Nov 14 '22 21:11

Eser