0

I have a json dataset that varies widely. it can have a field that is either an object or a list. how do I map these into a data model property if when I'm ingesting the data it can be either or. I can have a list of if else statements to check if a property is a list or object but for 10 fields that would grow rather big and make the code ugly.

field:{property1: 3, property2:4}

or

field:{[property1: 3, property2:4], [property1: 5, property2:6]}
Manny
  • 31
  • 3
  • Just have a model with `property` and `property2` and deserialize it to `List`. – Hassan Monjezi Nov 25 '20 at 21:20
  • Use `JsonConvert.Deserialize>(yourJson)`. – Hassan Monjezi Nov 25 '20 at 21:21
  • Assuming the objects in the list have the same schema as the single object (which isn't really clear from your question which lacks a [mcve]), this looks like a duplicate of [How to handle both a single item and an array for the same property using JSON.net](https://stackoverflow.com/q/18994685/3744182). Agree? – dbc Nov 25 '20 at 21:51

1 Answers1

0

if I understand you correctly, you receive data whose format is partially unknown to you.

var input = "{\"field\":{\"property1\": 3, \"property2\":4, \"property3\": 5, \"property4\":6}}";
var obj = JsonConvert.DeserializeObject<JObject>(input);
var res = new MyClass(){Fields = new List<MyField>()};
var field = obj.SelectToken("field") as JObject;
if(field != null)
{
    foreach (var item in field.Properties())
    {
        res.Fields.Add(new MyField()
        {
            Name = item.Name, 
            Value = item.Value.Value<int>()
        });
    }
}
public sealed class MyField
{
    public string Name { get; set; }
    public object Value { get; set; }
}

public sealed class MyClass
{
    public List<MyField> Fields { get; set; }

}
Stanislav
  • 459
  • 3
  • 6