Created
November 9, 2023 06:45
-
-
Save overing/66ae7aabf0a02f666329d1d2857ee6a6 to your computer and use it in GitHub Desktop.
Easy to deserialize JSON with anonymous object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
var json = """ | |
{ | |
"IntVal": 3, | |
"Inner": | |
{ | |
"FloatVal": 9.8, | |
"Message": "Test" | |
}, | |
"Items": | |
[ | |
{ | |
"Name": "A", | |
"Time": "2023-11-09T23:59:59" | |
}, | |
{ | |
"Name": "b", | |
"Time": "2023-11-29T11:59:59" | |
} | |
] | |
} | |
"""; | |
var obj = json.DeserializeJson(() => new | |
{ | |
IntVal = default(int), | |
Inner = new | |
{ | |
FloatVal = default(float), | |
Message = default(string) | |
}, | |
Items = new[] | |
{ | |
new | |
{ | |
Name = default(string), | |
Time = default(DateTime) | |
} | |
}, | |
}); | |
Console.WriteLine(obj!.Items[0].Time); | |
Console.ReadKey(); | |
public static class JsonExtensions | |
{ | |
public static T? DeserializeJson<T>(this string json, Func<T> _, System.Text.Json.JsonSerializerOptions? options = null) | |
=> System.Text.Json.JsonSerializer.Deserialize<T>(json, options); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment