Skip to content

Commit 9d17623

Browse files
authored
Removes newtonsoft (#6)
* Removes Newtonsoft.Json dependency in favor of System.Text.json
1 parent 7898608 commit 9d17623

File tree

16 files changed

+158
-164
lines changed

16 files changed

+158
-164
lines changed

Samples/HelloWorld/test.http

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# Mimicks a payload slack would send for app_mention events, like "@yourbot dostuff" in this case:
2-
GET http://localhost:5000/
2+
GET http://localhost:1337/
33
X-Slack-Request-Timestamp: 12331231
44
X-Slack-Signature: v0:abc123etcetc
55

@@ -12,3 +12,13 @@ X-Slack-Signature: v0:abc123etcetc
1212
"channel": "C92QZTVEF"
1313
}
1414
}
15+
16+
###
17+
# Verification request
18+
GET http://localhost:1337
19+
20+
{
21+
"token": "Jhj5dZrVaK7ZwHHjRyZWjbDl",
22+
"challenge": "3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P",
23+
"type": "url_verification"
24+
}

source/src/Slackbot.Net.Endpoints/Middlewares/Challenge.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
using System.Text.Json;
12
using System.Threading.Tasks;
23
using Microsoft.AspNetCore.Http;
34
using Microsoft.Extensions.Logging;
4-
using Newtonsoft.Json;
5+
56

67
namespace Slackbot.Net.Endpoints.Middlewares
78
{
@@ -20,7 +21,7 @@ public async Task Invoke(HttpContext context)
2021
_logger.LogInformation($"Handling challenge request. Challenge: {challenge}");
2122
context.Response.StatusCode = 200;
2223
context.Response.ContentType = "application/json";
23-
await context.Response.WriteAsync(JsonConvert.SerializeObject(new {challenge}));
24+
await context.Response.WriteAsync(JsonSerializer.Serialize(new {challenge}));
2425
}
2526

2627
public static bool ShouldRun(HttpContext ctx)

source/src/Slackbot.Net.Endpoints/Middlewares/HttpItemsManager.cs

Lines changed: 28 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
using System.IO;
22
using System.Text;
3+
using System.Text.Json;
34
using System.Threading.Tasks;
45
using Microsoft.AspNetCore.Http;
56
using Microsoft.Extensions.Logging;
6-
using Newtonsoft.Json;
7-
using Newtonsoft.Json.Linq;
87
using Slackbot.Net.Endpoints.Models.Events;
98
using Slackbot.Net.Endpoints.Models.Interactive;
109
using Slackbot.Net.Endpoints.Models.Interactive.BlockActions;
@@ -32,21 +31,23 @@ public async Task Invoke(HttpContext context)
3231

3332
if (body.StartsWith("{"))
3433
{
35-
var jObject = JObject.Parse(body);
34+
var jObject = JsonDocument.Parse(body);
3635
_logger.LogTrace(body);
37-
if (jObject.ContainsKey("challenge"))
36+
JsonElement challengeValue;
37+
bool isChallenge = jObject.RootElement.TryGetProperty("challenge", out challengeValue);
38+
if (isChallenge)
3839
{
39-
context.Items.Add(HttpItemKeys.ChallengeKey, jObject["challenge"]);
40+
context.Items.Add(HttpItemKeys.ChallengeKey, challengeValue);
4041
}
4142
else
4243
{
43-
var metadata = JsonConvert.DeserializeObject<EventMetaData>(body);
44-
if (jObject["event"] is JObject @event)
44+
var metadata = JsonSerializer.Deserialize<EventMetaData>(body, WebOptions);
45+
if (jObject.RootElement.GetProperty("event") is JsonElement @event)
4546
{
4647
var slackEvent = ToEventType(@event, body);
4748
context.Items.Add(HttpItemKeys.EventMetadataKey, metadata);
4849
context.Items.Add(HttpItemKeys.SlackEventKey, slackEvent);
49-
context.Items.Add(HttpItemKeys.EventTypeKey, @event["type"]);
50+
context.Items.Add(HttpItemKeys.EventTypeKey, @event.GetProperty("type"));
5051
}
5152
}
5253
}
@@ -58,7 +59,7 @@ public async Task Invoke(HttpContext context)
5859
_logger.LogTrace(body);
5960
var payloadJsonUrlEncoded = body.Remove(0,8);
6061
var decodedJson = System.Net.WebUtility.UrlDecode(payloadJsonUrlEncoded);
61-
var payload = JObject.Parse(decodedJson);
62+
var payload = JsonDocument.Parse(decodedJson).RootElement;
6263
var interactivePayloadTyped = ToInteractiveType(payload, body);
6364
context.Items.Add(HttpItemKeys.InteractivePayloadKey, interactivePayloadTyped);
6465
}
@@ -69,51 +70,54 @@ public async Task Invoke(HttpContext context)
6970
await _next(context);
7071
}
7172

72-
private static SlackEvent ToEventType(JObject eventJson, string raw)
73+
private static JsonSerializerOptions WebOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);
74+
75+
private static SlackEvent ToEventType(JsonElement eventJson, string raw)
7376
{
7477
var eventType = GetEventType(eventJson);
78+
string json = eventJson.ToString();
7579
switch (eventType)
7680
{
7781
case EventTypes.AppMention:
78-
return eventJson.ToObject<AppMentionEvent>();
82+
return JsonSerializer.Deserialize<AppMentionEvent>(json, WebOptions);
7983
case EventTypes.MemberJoinedChannel:
80-
return eventJson.ToObject<MemberJoinedChannelEvent>();
84+
return JsonSerializer.Deserialize<MemberJoinedChannelEvent>(json, WebOptions);
8185
case EventTypes.AppHomeOpened:
82-
return eventJson.ToObject<AppHomeOpenedEvent>();
86+
return JsonSerializer.Deserialize<AppHomeOpenedEvent>(json, WebOptions);
8387
default:
84-
UnknownSlackEvent unknownSlackEvent = eventJson.ToObject<UnknownSlackEvent>();
88+
UnknownSlackEvent unknownSlackEvent = JsonSerializer.Deserialize<UnknownSlackEvent>(json, WebOptions);
8589
unknownSlackEvent.RawJson = raw;
8690
return unknownSlackEvent;
8791
}
8892
}
8993

90-
private static Interaction ToInteractiveType(JObject payloadJson, string raw)
94+
private static Interaction ToInteractiveType(JsonElement payloadJson, string raw)
9195
{
9296
var eventType = GetEventType(payloadJson);
9397
switch (eventType)
9498
{
9599
case InteractionTypes.ViewSubmission:
96-
var viewSubmission = payloadJson.ToObject<ViewSubmission>();
100+
var viewSubmission = JsonSerializer.Deserialize<ViewSubmission>(payloadJson.GetString(), WebOptions);
97101

98-
var view = payloadJson["view"] as JObject;
99-
var viewState = view["state"] as JObject;;
100-
viewSubmission.ViewId = view.Value<string>("id");
102+
var view = payloadJson.GetProperty("view");
103+
var viewState = view.GetProperty("state");
104+
viewSubmission.ViewId = view.GetProperty("id").GetString();
101105
viewSubmission.ViewState = viewState;
102106
return viewSubmission;
103107
case InteractionTypes.BlockActions:
104-
return payloadJson.ToObject<BlockActionInteraction>();
108+
return JsonSerializer.Deserialize<BlockActionInteraction>(payloadJson.GetString(), WebOptions);
105109
default:
106-
var unknownSlackEvent = payloadJson.ToObject<UnknownInteractiveMessage>();
110+
var unknownSlackEvent = JsonSerializer.Deserialize<UnknownInteractiveMessage>(payloadJson.GetString(), WebOptions);
107111
unknownSlackEvent.RawJson = raw;
108112
return unknownSlackEvent;
109113
}
110114
}
111115

112-
public static string GetEventType(JObject eventJson)
116+
public static string GetEventType(JsonElement eventJson)
113117
{
114-
if (eventJson != null)
118+
if (eventJson.ValueKind != JsonValueKind.Null)
115119
{
116-
return eventJson["type"].Value<string>();
120+
return eventJson.GetProperty("type").GetString();
117121
}
118122

119123
return "unknown";
Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
1-
using Newtonsoft.Json;
2-
31
namespace Slackbot.Net.Endpoints.Models.Interactive
42
{
53
public class Team
64
{
7-
[JsonProperty("id")]
85
public string Id { get; set; }
96
}
107
}
Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
1-
using Newtonsoft.Json;
2-
31
namespace Slackbot.Net.Endpoints.Models.Interactive
42
{
53
public class User
64
{
7-
[JsonProperty("user_id")]
85
public string User_Id { get; set; }
96
}
107
}
Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
2-
using Newtonsoft.Json.Linq;
1+
using System.Text.Json;
32

43
namespace Slackbot.Net.Endpoints.Models.Interactive.ViewSubmissions
54
{
@@ -9,6 +8,6 @@ public class ViewSubmission : Interaction
98
public User User { get; set; }
109

1110
public string ViewId { get; set; }
12-
public JObject ViewState { get; set; }
11+
public JsonElement ViewState { get; set; }
1312
}
1413
}

source/src/Slackbot.Net.Endpoints/Slackbot.Net.Endpoints.csproj

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,7 @@
2020
</PropertyGroup>
2121

2222
<ItemGroup>
23-
<FrameworkReference Include="Microsoft.AspNetCore.App" />
24-
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
23+
<FrameworkReference Include="Microsoft.AspNetCore.App" />
2524
</ItemGroup>
2625

2726
<ItemGroup>

source/src/Slackbot.Net.SlackClients.Http/Extensions/HttpClientExtensions.cs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,24 @@
33
using System.Linq;
44
using System.Net.Http;
55
using System.Text;
6+
using System.Text.Json;
7+
using System.Text.Json.Serialization;
68
using System.Threading.Tasks;
7-
using Newtonsoft.Json;
8-
using Newtonsoft.Json.Serialization;
9+
910
using Slackbot.Net.SlackClients.Http.Exceptions;
1011
using Slackbot.Net.SlackClients.Http.Models.Responses;
1112

1213
namespace Slackbot.Net.SlackClients.Http.Extensions
1314
{
1415
internal static class HttpClientExtensions
1516
{
16-
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
17+
private static readonly JsonSerializerOptions JsonSerializerSettings = new JsonSerializerOptions(JsonSerializerDefaults.Web)
1718
{
18-
ContractResolver = new CamelCasePropertyNamesContractResolver(),
19-
NullValueHandling = NullValueHandling.Ignore
19+
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
2020
};
21-
2221
public static async Task<T> PostJson<T>(this HttpClient httpClient, object payload, string api, Action<string> logger = null) where T:Response
2322
{
24-
var serializedObject = JsonConvert.SerializeObject(payload, JsonSerializerSettings);
23+
var serializedObject = JsonSerializer.Serialize(payload, JsonSerializerSettings);
2524
var httpContent = new StringContent(serializedObject, Encoding.UTF8, "application/json");
2625
var request = new HttpRequestMessage(HttpMethod.Post, api)
2726
{
@@ -40,7 +39,7 @@ public static async Task<T> PostJson<T>(this HttpClient httpClient, object paylo
4039

4140
response.EnsureSuccessStatusCode();
4241

43-
var resObj = JsonConvert.DeserializeObject<T>(responseContent, JsonSerializerSettings);
42+
var resObj = JsonSerializer.Deserialize<T>(responseContent, JsonSerializerSettings);
4443

4544
if (!resObj.Ok)
4645
{
@@ -75,7 +74,7 @@ public static async Task<T> PostParametersAsForm<T>(this HttpClient httpClient,
7574

7675
response.EnsureSuccessStatusCode();
7776

78-
var resObj = JsonConvert.DeserializeObject<T>(responseContent, JsonSerializerSettings);
77+
var resObj = JsonSerializer.Deserialize<T>(responseContent, JsonSerializerSettings);
7978

8079
if(!resObj.Ok)
8180
throw new WellKnownSlackApiException(error: $"{resObj.Error}", responseContent:responseContent);

source/src/Slackbot.Net.SlackClients.Http/Models/Requests/ChatPostMessage/ChatPostMessageRequest.cs

Lines changed: 27 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -21,38 +21,38 @@ public class ChatPostMessageRequest
2121

2222
public class Attachment
2323
{
24-
public string callback_id;
25-
public string fallback;
26-
public string color;
27-
public string pretext;
28-
public string author_name;
29-
public string author_link;
30-
public string author_icon;
31-
public string title;
32-
public string title_link;
33-
public string text;
34-
public Field[] fields;
35-
public string image_url;
36-
public string thumb_url;
37-
public string[] mrkdwn_in;
38-
public AttachmentAction[] actions;
39-
public string footer;
40-
public string footer_icon;
24+
public string callback_id{ get; set; }
25+
public string fallback { get; set; }
26+
public string color { get; set; }
27+
public string pretext { get; set; }
28+
public string author_name { get; set; }
29+
public string author_link { get; set; }
30+
public string author_icon { get; set; }
31+
public string title { get; set; }
32+
public string title_link { get; set; }
33+
public string text { get; set; }
34+
public Field[] fields { get; set; }
35+
public string image_url { get; set; }
36+
public string thumb_url { get; set; }
37+
public string[] mrkdwn_in { get; set; }
38+
public AttachmentAction[] actions { get; set; }
39+
public string footer { get; set; }
40+
public string footer_icon { get; set; }
4141
}
4242

4343
public class Field
4444
{
45-
public string title;
46-
public string value;
47-
public bool @short;
45+
public string title { get; set; }
46+
public string value { get; set; }
47+
public bool @short { get; set; }
4848
}
4949

5050
public class AttachmentAction
5151
{
5252
public string type = "button";
53-
public string style;
54-
public string value;
55-
public ActionConfirm confirm;
53+
public string style { get; set; }
54+
public string value { get; set; }
55+
public ActionConfirm confirm { get; set; }
5656

5757
public AttachmentAction(string name, string text)
5858
{
@@ -67,9 +67,9 @@ public AttachmentAction(string name, string text)
6767

6868
public class ActionConfirm
6969
{
70-
public string title;
71-
public string text;
72-
public string ok_text;
73-
public string dismiss_text;
70+
public string title { get; set; }
71+
public string text { get; set; }
72+
public string ok_text { get; set; }
73+
public string dismiss_text { get; set; }
7474
}
7575
}

source/src/Slackbot.Net.SlackClients.Http/Models/Requests/ViewPublish/ViewPublishRequest.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
using Newtonsoft.Json;
2-
31
namespace Slackbot.Net.SlackClients.Http.Models.Requests.ViewPublish
42
{
53
public class ViewPublishRequest
@@ -8,8 +6,7 @@ public ViewPublishRequest(string userId)
86
{
97
User_Id = userId;
108
}
11-
12-
[JsonProperty("user_id")]
9+
1310
public string User_Id { get; }
1411

1512
public View View { get; set; }

0 commit comments

Comments
 (0)