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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With