Skip to content

Instantly share code, notes, and snippets.

View JsonParseConsole.cs
class Program
{
static void Main(string[] args)
{
var jsonString = CreateMockJsonString();
var isJsonFormat = jsonString.JsonTryParse<BaseModel<User>>(out var jsonResult);
if (!isJsonFormat)
{
Console.WriteLine($"{jsonString} is not JSON format !");
}
View User.cs
public class User
{
[JsonPropertyName("Name")]
public string Name { get; set; }
[JsonPropertyName("Age")]
public int Age { get; set; }
}
View BaseModel.cs
public class BaseModel<T> where T : class
{
[JsonPropertyName("Code")]
public int Code { get; set; } = -1;
[JsonPropertyName("Msg")]
public string Message { get; set; }
[JsonPropertyName("Response")]
public T Response { get; set; }
}
View JsonParseExtension.cs
public static class JsonParseExtension
{
public static bool JsonTryParse<T>(this string jsonString, out T result) where T : class
{
try
{
result = JsonSerializer.Deserialize<T>(jsonString);
return true;
}
catch(Exception e)
View ResponseFailure.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
View ResponseSuccess.json
{
"Code": 0,
"Msg": "Success!",
"Response": {
"Name": "Andy",
"Age": 28
}
}