File tree Expand file tree Collapse file tree 2 files changed +71
-0
lines changed
ExtensionMethodEncapsulation
ExtensionMethodEncapsulation Expand file tree Collapse file tree 2 files changed +71
-0
lines changed Original file line number Diff line number Diff line change
1
+ using Newtonsoft . Json ;
2
+
3
+ namespace ExtensionMethodEncapsulation
4
+ {
5
+ public static class JsonExtensions
6
+ {
7
+ /// <summary>
8
+ /// Method to encapsulate how you serialize your JSON object.
9
+ /// </summary>
10
+ /// <typeparam name="T">The type of the object/POCO you wish to convert to JSON.</typeparam>
11
+ /// <param name="obj">The JSON object.</param>
12
+ /// <returns></returns>
13
+ public static string SerializeAsJsonString < T > ( this T obj )
14
+ {
15
+ var jsonString = JsonConvert . SerializeObject ( obj ) ;
16
+
17
+ return jsonString ;
18
+ }
19
+
20
+ /// <summary>
21
+ /// Method to encapsulate how you deserialize your JSON string.
22
+ /// </summary>
23
+ /// <typeparam name="T">The strong typed object represantation of your JSON string/object</typeparam>
24
+ /// <param name="json">The string representing your JSON object.</param>
25
+ /// <returns></returns>
26
+ public static T DeserializeJsonString < T > ( this string json )
27
+ {
28
+ var deserializedObject = JsonConvert . DeserializeObject < T > ( json ) ;
29
+
30
+ return deserializedObject ;
31
+ }
32
+ }
33
+ }
Original file line number Diff line number Diff line change
1
+ using System ;
2
+ using System . Globalization ;
3
+
4
+ using Newtonsoft . Json ;
5
+
6
+ namespace NoEncalsulation
7
+ {
8
+ class Program
9
+ {
10
+ public class SomeKindaPoco
11
+ {
12
+ public int Id { get ; set ; }
13
+ public string SomeKindaMessage { get ; set ; }
14
+ }
15
+
16
+ static void Main ( string [ ] args )
17
+ {
18
+ var obj = new SomeKindaPoco ( )
19
+ {
20
+ Id = 1 ,
21
+ SomeKindaMessage = "Skullduggery"
22
+ } ;
23
+
24
+ var jsonString = JsonConvert . SerializeObject ( obj ) ;
25
+
26
+ Console . WriteLine ( "Now we got the POCO into a JSON string in ONE LINE !! Whee !!!!" ) ;
27
+ Console . WriteLine ( jsonString ) ;
28
+
29
+ var strongTypedJsonObject = JsonConvert . DeserializeObject < SomeKindaPoco > ( jsonString ) ;
30
+
31
+ Console . WriteLine ( "Now we got the JSON string back into a POCO, WHEEEEE !!!!" ) ;
32
+ Console . WriteLine ( "ID Property : " + strongTypedJsonObject . Id . ToString ( CultureInfo . InvariantCulture ) ) ;
33
+ Console . WriteLine ( "SomeKindaMessageProperty : " + strongTypedJsonObject . SomeKindaMessage ) ;
34
+
35
+ Console . ReadLine ( ) ;
36
+ }
37
+ }
38
+ }
You can’t perform that action at this time.
0 commit comments