I'm building a console application/windows service that consumes json from an API and then deserializes to objects. The service is triggered by a timer that runs on interval, so each time the timer elapses the API is called and response json is deserialized to be compared against objects in memory to see if anything has changed (no event triggers on the source API).
The problem is that each time json is deserialized, the memory usage of the application increases unexpectedly.
Is this a structure problem, a misuse of Json.Net, or a memory leak in the Json.Net implementation?
Tried "using()" on JOjbects and JTokens but they're not disposable. Is there no garbage collection? Also considered removing the "response","enrollment", and "enrollment" levels from the json string manually via search or something but that seems like it should be unnecessary.
Json:
{
"response":{
"code":"OK",
"enrollments":{
"enrollment":[
{
"id":"enrollment_id",
...,
"course":{...},
"user":{...}
},
{
"id":"enrollment_id",
...,
"course":{...},
"user":{...}
},
...]}}}
Models:
[Serializable]
class Enrollment
{
props ... { get; set; }
... and some serializable objects below
public Course Course { get; set; }
public User User { get; set; }
}
Json Handler
public static List<Enrollment> JToEnrollments(string json)
{
List<Enrollment> enrollments = new List<Enrollment>();
JObject jo = JObject.Parse(json);
JToken eList = jo["response"]["enrollments"]["enrollment"];
string jString = "";
foreach (var e in eList)
{
jString = JsonConvert.SerializeObject(e);
Enrollment enrollment = JsonConvert.DeserializeObject<Enrollment>(jString);
enrollments.Add(enrollment);
}
jo = null; // attempt at cleanup
eList = null; // attempt at cleanup
return enrollments;
}
Desired result is a temporary List object that will be compared to a List object in memory. The List in memory will then be updated if necessary and the temporary List is disposed.
Note: Looking at Memory Usage, one of the larger increases in memory is a List that has stuff like Action, NewtonSoft.Json.Serialization.DynamicValueProvider inside.
>();` which would be even simpler.
>(); is much more elegant and seems to have reduced the memory usage quite a bit, thank you. Also, the json string is some 100k+ characters, next I'm going to look into (de)serializing from stream as recommended in the Json.NET documentation. Edit:To clarify, do all strings over 42.5k characters go to large object heap or just jStrings?
– Dogmabase Aug 07 '19 at 01:20