Commit b992e1b3 authored by 阿星Plus's avatar 阿星Plus

GetObjectFromJsonFile

parent bea09e2d
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Plus.Extensions.Serialization;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
/// <summary>
......@@ -112,4 +114,22 @@ public static class Extensions
return JsonConvert.DeserializeObject(value, type, settings);
}
public static async Task<T> GetObjectFromJsonFile<T>(string filePath, string key = "") where T : new()
{
if (!File.Exists(filePath))
{
return new T();
}
using (StreamReader reader = new StreamReader(filePath))
{
var json = await reader.ReadToEndAsync();
if (string.IsNullOrEmpty(key))
{
return JsonConvert.DeserializeObject<T>(json);
}
return !(JsonConvert.DeserializeObject<object>(json) is JObject obj) ? new T() : JsonConvert.DeserializeObject<T>(obj[key].ToString());
}
}
}
\ No newline at end of file
......@@ -17,7 +17,7 @@
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageTags>plus;plus.extensions;plus.extensions.serialization;.netcoreplus;</PackageTags>
<PackageReleaseNotes>Plus.Extensions.Serialization</PackageReleaseNotes>
<Version>1.0.2</Version>
<Version>1.0.3</Version>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment