C# MAUI怎么解析JSON数据 MAUI JSON序列化教程

来源:这里教程网 时间:2026-02-21 17:38:34 作者:

在 .NET MAUI 中解析 JSON 数据,最推荐的方式是使用内置的 System.Text.Json(.NET 6+ 默认 JSON 库),它轻量、高性能、无需额外 NuGet 包,且与 MAUI 完全兼容。

定义匹配的 C# 类型

JSON 解析前必须先有对应的数据模型。比如你收到如下 JSON:

{"name":"张三","age":28,"isActive":true}

就应创建一个匹配的类:

public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
    public bool IsActive { get; set; }
}

注意:属性名默认需与 JSON 字段名一致(区分大小写),如不一致可用

[JsonPropertyName("user_name")]
特性标记。

从字符串反序列化为对象

这是最常见场景,例如从 API 响应或本地 JSON 文件读取后解析:

确保已引入命名空间:
using System.Text.Json;
调用
JsonSerializer.Deserialize<t>(jsonString)</t>
建议加 try-catch 处理格式错误

示例代码:

string json = @"{""name"":""李四"",""age"":30,""isActive"":false}";
try
{
    User user = JsonSerializer.Deserialize<User>(json);
    Console.WriteLine($"{user.Name}, {user.Age}");
}
catch (JsonException ex)
{
    Console.WriteLine("JSON 格式错误:" + ex.Message);
}

处理数组和嵌套结构

JSON 数组直接映射为 C# 的

List<t></t>
T[]
;嵌套对象则用子类表示。

例如解析:
[{"id":1,"profile":{"nick":"小王","score":95}}]

对应模型:

public class Player
{
    public int Id { get; set; }
    public Profile Profile { get; set; }
}
<p>public class Profile
{
public string Nick { get; set; }
public int Score { get; set; }
}

解析方式不变:

List<Player> players = JsonSerializer.Deserialize<List<Player>>(jsonString);

从文件或网络加载 JSON 后解析

MAUI 支持跨平台文件访问(如

FileSystem.AppDataDirectory
)和 HTTP 请求:

读取本地 JSON 文件(如
data.json
):
string path = Path.Combine(FileSystem.AppDataDirectory, "data.json");
string json = await File.ReadAllTextAsync(path);
var data = JsonSerializer.Deserialize<MyModel>(json);
从网络获取(配合
HttpClient
):
using var client = new HttpClient();
string json = await client.GetStringAsync("https://api.example.com/users");
var users = JsonSerializer.Deserialize<List<User>>(json);

注意:网络请求请放在异步方法中,并在 UI 线程安全地更新界面(如用

MainThread.InvokeOnMainThreadAsync
)。

基本上就这些。System.Text.Json 在 MAUI 中开箱即用,不需要 Newtonsoft.Json(除非遗留项目强依赖)。只要模型对得上、注意异常处理、分清同步/异步上下文,JSON 解析很稳。

相关推荐