My JSON object consists of consistent attributes udid
, date
, event_id
and varying but known attributes inside parameters
. Below there are two objects:
{
"udid": "70baf33f-f011-44ee-b35a-6064b5ab468d",
"date": "2018-01-01",
"event_id": 2,
"parameters": {
"gender": "male",
"age": 13,
"country": "India"
}
},
{
"udid": "70baf33f-f011-44ee-b35a-6064b5ab468d",
"date": "2018-01-01",
"event_id": 1,
"parameters": {}
}
Such JSON can be represented inside one object, if I move parameters on the top level like that:
public class Event
{
[Key]
public int Id { get; set; }
public string udid { get; set; }
public DateTime date { get; set; }
public int event_id { get; set;}
public string gender { get; set; }
public int age { get; set; }
public string country { get; set; }
public int stage { get; set; }
public bool win { get; set; }
public int time { get; set; }
public int income { get; set; }
public string name { get; set; }
public double price { get; set; }
public string item { get; set; }
}
So, how do I deserialize that in efficient way, because I have like 30 millions of such records? I'm using newtonsoft.json.
Edit:
I end up creating three objects (nested Parameters
inside EventNested
) and flattened Event
as Liam adviced. I casually deserialized json into EventNested and then remapped it into Event using this bulky LINQ expression:
List<EventNested> eventsNested = JsonConvert.DeserializeObject<List<EventNested>>(json);
List<Event> events = eventsNested.Select(x=> new Event {
date = x.date,
udid = x.udid,
event_id = x.event_id,
parametersAge = x.Parameters.age,
parametersCountry = x.Parameters.country,
parametersGender = x.Parameters.gender,
parametersIncome = x.Parameters.income,
parametersItem = x.Parameters.item,
parametersName = x.Parameters.name,
parametersPrice = x.Parameters.price,
parametersStage = x.Parameters.stage,
parametersTime = x.Parameters.time,
parametersWin = x.Parameters.win
} ).ToList();
Just nest one object inside the other. (If you're using EF, maybe it would be better to have 2 separate Events: one for your DbSet (without nested object) and another as a JSON data contract.)
public class Event
{
//.. the rest of your attributes here
public EventParameters Parameters { get; set; }
}
public class EventParameters
{
public int? Age { get; set; } // If such parameter may not exist in your JSON, ensure it to be nullable in your POCO.
public string Country { get; set; }
public string Gender { get; set; }
}