/// <summary>
/// 新建全部值为null的Json对象并写入指定路径, 使用类中属性作为Key, 如果属性是一个类型, 那将作为Json的子集包括它, 但子类型不能继续含有子类型
/// </summary>
/// <typeparam name="T">Json对象的内容, 使用类型, 类型中的属性可以是一个类型</typeparam>
/// <param name="strSavePath">如果需要保存文件, 输入保存的路径, 不包含文件名</param>
/// <param name="strFilename">如果需要保存文件, 输入文件名, 不包含.json后缀</param>
/// <param name="strNamespace">如果类型内有子类型, 则在这输入子类型所在的命名空间</param>
/// <returns>Json 字符串</returns>
public static string CreateJson<T>(string strSavePath = "", string strFilename = "", string strNamespace = "")
{
try
{
JObject oJson = new JObject(); //新建Json对象
Type jsonType = typeof(T); //获取T类型
PropertyInfo[] propertys = jsonType.GetProperties(); //得到T类型中所有属性
foreach (PropertyInfo item in propertys) //遍历属性
{
if (!string.IsNullOrEmpty(strNamespace)) //判断是否填写命名空间
{
// 获取命名空间
// 获取当前的属性包括命名空间名
// 通过获取到的命名空间中读取属性名, 命名空间下没有则返回null
// 为null说明是值类型等基本类型或String, 对于它们直接创建
//
Assembly assembly = Assembly.Load(strNamespace);
string strType = item.PropertyType.FullName;
Type type = assembly.GetType(strType);
if (type == null)
oJson.Add(new JProperty(item.Name, null));
else
{
JObject oChildJson = new JObject()
C# LitJson新建Json字符串与Json数组, 或者读取
最新推荐文章于 2022-12-14 09:07:15 发布