跳到主要内容

Json

public class UserInfo
{
public string UserName { get; set; }
public int Age { get; set; }
}

ToObj<T>

备注

字符串转为指定的对象

string userInfo = @"
{
""userName"": ""ABCD"",
""age"": 23
}";
var user = userInfo.ToObj<UserInfo>();
// user.UserName == "ABCD";
// user.Age == 23;

ToObjCollection<T>

备注

字符串转为对象集合

string userInfo = @"
[
{
""userName"": ""ABCD"",
""age"": 23
}
]";
IEnumerable<UserInfo> user = userInfo.ToObjCollection<UserInfo>();
// user.First().UserName = "ABCD";
// user.First().Age = 23;

ToJson

备注

对象转json字符串

UserInfo user = new()
{
UserName = "ABCD",
Age = 23
};
var jsonString = user.ToJson().Trim();
// "{\"userName\":\"ABCD\",\"age\":23}"

JsonMap

备注

通过json的序列化反序列化实现的map功能

public class UserInfoTwo
{
public string UserName { get; set; }
public int Age { get; set; }
}

UserInfo user = new()
{
UserName = "ABCD",
Age = 23
};
UserInfoTwo user2 = user.JsonMap<UserInfoTwo>();

JsonNode

备注

当拿到的 json 对象比较复杂时, 相比于构建对应的 class, 使用 JsonNode 更加方便

string userInfo = @"
[
{
""userName"": ""ABCD"",
""age"": 23
}
]";
JsonNode userNode = userInfo.ToJsonNode();
JsonArray userArray = userNode.ToJsonArray();
JsonObject userObject = userNode.ToJsonObject();