Skip to content

Instantly share code, notes, and snippets.

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 !");
}
public class User
{
[JsonPropertyName("Name")]
public string Name { get; set; }
[JsonPropertyName("Age")]
public int Age { get; set; }
}
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; }
}
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)
<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>
{
"Code": 0,
"Msg": "Success!",
"Response": {
"Name": "Andy",
"Age": 28
}
}