备注:可直接在控制台输出,不需要引用第三方nuget包
using System;
using System.Collections.Generic;
using System.Text.Encodings.Web;
using System.Text.Json;
class Program
{
public class Data
{
public string MoCategorySelect { get; set; }
public string SubcategorySelect { get; set; }
}
static void Main()
{
string data = @"{'MoCategorySelect':'AA','SubcategorySelect':'111'}";
//任务一:sting=>json
JsonDocument jsonDoc = GetJsonData(data);
//任务二:string(json形式)=>dict(字典)
var dict = GetDictionary(data);
//任务三:json=>dict
var dict2 = GetDictionary(jsonDoc);
//任务四:json=>string
var stringdata = GetStringByJson(jsonDoc);
Console.WriteLine(stringdata);
//任务五:dict=>json
JsonDocument json = GetJsonData(dict);
//任务六:T=>Json
var entity = new Data() { MoCategorySelect = "AA", SubcategorySelect = "111" };
var result = GetJsonData(entity);
//任务七:JSON=>T
var result2 = GetEntity<Data>(jsonDoc);
;
}
private static T GetEntity<T>(JsonDocument jsonDoc) where T : class
{
string jsonString = GetStringByJson(jsonDoc);
T entity = JsonSerializer.Deserialize<T>(jsonString);//转换时严格遵循大小写
return entity;
}
private static JsonDocument GetJsonData(Data entity)
{
string jsonString = JsonSerializer.Serialize(entity);// 对象转换为 JSON 字符串
return GetJsonData(jsonString);//JSON字符串=>json
}
private static Dictionary<string, string> GetDictionary(JsonDocument jsonDoc)
{
return GetDictionary(GetStringByJson(jsonDoc));
}
private static string GetStringByJson(JsonDocument jsonDoc)
{
var options = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping // 禁用 Unicode 转义
};
// 直接序列化 JsonDocument 的根元素
string jsonString = JsonSerializer.Serialize(jsonDoc.RootElement, options);
return jsonString;
}
private static JsonDocument GetJsonData(Dictionary<string, string> dict)
{
string jsonString = JsonSerializer.Serialize(dict, new JsonSerializerOptions
{
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
});
JsonDocument json = JsonDocument.Parse(jsonString);
return json;
}
private static JsonDocument GetJsonData(string data)
{
return JsonDocument.Parse(data.Replace('\'', '\"'));
}
private static Dictionary<string, string> GetDictionary(string data)
{
var jsonObject = JsonDocument.Parse(data.Replace('\'', '\"')).RootElement;
var dict = new Dictionary<string, string>();
foreach (var property in jsonObject.EnumerateObject())
{
dict[property.Name] = property.Value.GetString();
}
return dict;
}
}
标签:实体类,string,C#,JsonDocument,json,JSON,jsonDoc,dict,var
From: https://blog.csdn.net/m0_67412019/article/details/141187604