Skip to content

Commit 339c31a

Browse files
committed
Add Helpers.PopulateObjects to create a list of Things with a WebAgent
1 parent 9b39c59 commit 339c31a

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

RedditSharp/Helpers/Helpers.PopulateObject.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
using Newtonsoft.Json;
22
using Newtonsoft.Json.Linq;
33
using System;
4+
using System.Collections.Generic;
5+
using System.Linq;
6+
using RedditSharp.Interfaces;
47

58
namespace RedditSharp
69
{
@@ -22,5 +25,24 @@ internal static void PopulateObject(JToken json, object obj)
2225
jsonSerializer.Populate(reader, obj);
2326
}
2427
}
28+
29+
internal static List<T> PopulateObjects<T>(JToken json, IWebAgent webAgent)
30+
where T : ISettableWebAgent, new()
31+
{
32+
if (json.Type != JTokenType.Array)
33+
throw new ArgumentException("must be of type array", nameof(json));
34+
35+
var objects = new List<T>();
36+
37+
for (var i = 0; i < json.Count(); i++)
38+
{
39+
var item = new T();
40+
PopulateObject(json[i], item);
41+
item.WebAgent = webAgent;
42+
objects.Add(item);
43+
}
44+
45+
return objects;
46+
}
2547
}
2648
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
using Newtonsoft.Json;
2+
3+
namespace RedditSharp.Interfaces
4+
{
5+
internal interface ISettableWebAgent
6+
{
7+
[JsonIgnore]
8+
IWebAgent WebAgent { set; }
9+
}
10+
}

0 commit comments

Comments
 (0)