Skip to content

Commit

Permalink
[feat]新增IJsonHost.Parse,分析Json字符串得到字典或列表
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Jul 8, 2024
1 parent 8aa52c8 commit 0a2df92
Show file tree
Hide file tree
Showing 10 changed files with 69 additions and 28 deletions.
5 changes: 4 additions & 1 deletion NewLife.Core/Collections/CollectionHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,10 @@ JsonValueKind.Number when item.Value.GetRawText().Contains('.') => item.Value.Ge
}

#if NETCOREAPP
static IList<Object?> ToArray(JsonElement element)
/// <summary>Json对象转为数组</summary>
/// <param name="element"></param>
/// <returns></returns>
public static IList<Object?> ToArray(this JsonElement element)
{
var list = new List<Object?>();
foreach (var item in element.EnumerateArray())
Expand Down
11 changes: 6 additions & 5 deletions NewLife.Core/Http/TinyHttpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -383,13 +383,15 @@ private HttpRequest BuildRequest(Uri baseAddress, String method, String action,
if (typeof(TResult).IsBaseType()) return str.ChangeType<TResult>();

// 反序列化
//var dic = JsonParser.Decode(str);
var dic = JsonHost.Decode(str);
var obj = JsonHost.Parse(str);
if (obj is TResult result) return result;

var dic = obj as IDictionary<String, Object?>;
if (dic == null || !dic.TryGetValue("data", out var data)) throw new InvalidDataException("Unrecognized response data");

if (dic.TryGetValue("result", out var result))
if (dic.TryGetValue("result", out var result2))
{
if (result is Boolean res && !res) throw new InvalidOperationException($"remote error: {data}");
if (result2 is Boolean res && !res) throw new InvalidOperationException($"remote error: {data}");
}
else if (dic.TryGetValue("code", out var code))
{
Expand All @@ -402,7 +404,6 @@ private HttpRequest BuildRequest(Uri baseAddress, String method, String action,

if (data == null) return default;

//return JsonHelper.Convert<TResult>(data);
return JsonHost.Convert<TResult>(data);
}
#endregion
Expand Down
27 changes: 21 additions & 6 deletions NewLife.Core/Remoting/ApiHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,6 @@ public static HttpContent BuildContent(Packet pk)
// 400响应可能包含错误信息
if (!msg.IsNullOrEmpty() && msg.StartsWith("{") && msg.EndsWith("}"))
{
//var dic = JsonParser.Decode(msg);
var dic = jsonHost.Decode(msg);
if (dic != null)
{
Expand Down Expand Up @@ -286,15 +285,32 @@ public static HttpContent BuildContent(Packet pk)
if (response.IsNullOrEmpty()) return default;

var rtype = typeof(TResult);

jsonHost ??= JsonHelper.Default;
var dic = response.StartsWith("<") && response.EndsWith(">") ? XmlParser.Decode(response) : jsonHost.Decode(response);
if (dic == null) return default;

IDictionary<String, Object?>? dic = null;
if (response.StartsWith("<") && response.EndsWith(">"))
{
// XML反序列化
dic = XmlParser.Decode(response);
}
else
{
// Json反序列化,可能是字典或列表
var obj = jsonHost.Parse(response);

// 如果没有data部分。可能是 IDictionary<String, Object?> 或 IList<Object?> ,或其它
if (dataName.IsNullOrEmpty() && obj is TResult result2) return result2;

dic = obj as IDictionary<String, Object?>;
}

//if (dic == null) return default;
if (dic == null) throw new InvalidCastException($"Unable to convert to type [{typeof(TResult)}]! {response.Cut(64)}");

var nodata = dataName.IsNullOrEmpty() || !dic.ContainsKey(dataName);

// 未指定有效数据名时,整体返回
if (nodata && rtype == typeof(IDictionary<String, Object>)) return (TResult)dic;
if (nodata && dic is TResult result3) return result3;

// 如果没有指定数据名,或者结果中不包含数据名,则整个字典作为结果数据
var data = nodata ? dic : dic[dataName];
Expand Down Expand Up @@ -353,7 +369,6 @@ public static HttpContent BuildContent(Packet pk)
if (data is not IDictionary<String, Object> and not IList<Object>)
throw new InvalidDataException($"Unrecognized response data [{(data as String)?.Cut(64)}] for [{typeof(TResult).Name}]");

//return JsonHelper.Convert<TResult>(data);
return jsonHost.Convert<TResult>(data);
}

Expand Down
24 changes: 24 additions & 0 deletions NewLife.Core/Serialization/Json/IJsonHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ public interface IJsonHost
/// <returns></returns>
Object? Convert(Object obj, Type targetType);

/// <summary>分析Json字符串得到字典或列表</summary>
/// <param name="json"></param>
/// <returns></returns>
Object? Parse(String json);

/// <summary>分析Json字符串得到字典</summary>
/// <param name="json"></param>
/// <returns></returns>
Expand Down Expand Up @@ -202,6 +207,11 @@ public static String Format(String json)
return (T?)jsonHost.Convert(obj, typeof(T));
}

/// <summary>分析Json字符串得到字典或列表</summary>
/// <param name="json"></param>
/// <returns></returns>
public static Object? Parse(String json) => Default.Parse(json);

/// <summary>分析Json字符串得到字典</summary>
/// <param name="json"></param>
/// <returns></returns>
Expand Down Expand Up @@ -241,6 +251,11 @@ public class FastJson : IJsonHost
/// <returns></returns>
public Object? Convert(Object obj, Type targetType) => new JsonReader { Provider = ServiceProvider }.ToObject(obj, targetType, null);

/// <summary>分析Json字符串得到字典或列表</summary>
/// <param name="json"></param>
/// <returns></returns>
public Object? Parse(String json) => new JsonParser(json).Decode();

/// <summary>分析Json字符串得到字典</summary>
/// <param name="json"></param>
/// <returns></returns>
Expand Down Expand Up @@ -381,6 +396,15 @@ public String Write(Object value, JsonOptions jsonOptions)
/// <returns></returns>
public Object? Convert(Object obj, Type targetType) => new JsonReader { Provider = ServiceProvider }.ToObject(obj, targetType, null);

/// <summary>分析Json字符串得到字典或列表</summary>
/// <param name="json"></param>
/// <returns></returns>
public Object? Parse(String json)
{
var doc = JsonDocument.Parse(json);
return doc.RootElement.ToArray();
}

/// <summary>分析Json字符串得到字典</summary>
/// <param name="json"></param>
/// <returns></returns>
Expand Down
2 changes: 0 additions & 2 deletions NewLife.Core/Serialization/Json/JsonWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ public static String ToJson(Object obj, Boolean indented = false, Boolean nullVa
jw.WriteValue(obj);

var json = jw._Builder.ToString();
//if (indented) json = JsonHelper.Format(json);

return json;
}
Expand All @@ -118,7 +117,6 @@ public static String ToJson(Object obj, JsonOptions jsonOptions)
jw.WriteValue(obj);

var json = jw._Builder.ToString();
//if (indented) json = JsonHelper.Format(json);

return json;
}
Expand Down
4 changes: 2 additions & 2 deletions Samples/Zero.HttpServer/Zero.HttpServer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="NewLife.Redis" Version="5.6.2024.402" />
<PackageReference Include="NewLife.Stardust" Version="2.9.2024.402" />
<PackageReference Include="NewLife.Redis" Version="5.7.2024.701" />
<PackageReference Include="NewLife.Stardust" Version="3.0.2024.707" />
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions Samples/Zero.Server/Zero.Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="NewLife.Redis" Version="5.6.2024.402" />
<PackageReference Include="NewLife.Stardust" Version="2.9.2024.402" />
<PackageReference Include="NewLife.Redis" Version="5.7.2024.701" />
<PackageReference Include="NewLife.Stardust" Version="3.0.2024.707" />
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions Test/Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
<None Remove="Model\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="NewLife.Stardust" Version="2.9.2023.1103" />
<PackageReference Include="NewLife.XCode" Version="11.10.2024.101" />
<PackageReference Include="NewLife.Stardust" Version="3.0.2024.707" />
<PackageReference Include="NewLife.XCode" Version="11.13.2024.701" />
<!--<PackageReference Include="System.Speech" Version="7.0.0" />-->
</ItemGroup>
<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion Test2/Test2.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
<None Remove="Model\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="NewLife.Stardust" Version="2.9.2023.1103" />
<PackageReference Include="NewLife.Stardust" Version="3.0.2024.707" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\NewLife.Core\NewLife.Core.csproj" />
Expand Down
14 changes: 7 additions & 7 deletions XUnitTest.Core/XUnitTest.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@
<EmbeddedResource Include="IO\excel.xlsx" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="BouncyCastle.Cryptography" Version="2.3.1" />
<PackageReference Include="BouncyCastle.Cryptography" Version="2.4.0" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Moq" Version="4.20.69" />
<PackageReference Include="NewLife.Modbus" Version="1.6.2023.511" />
<PackageReference Include="NewLife.UnitTest" Version="1.0.2023.905" />
<PackageReference Include="xunit" Version="2.6.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3">
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="NewLife.Modbus" Version="1.8.2024.217" />
<PackageReference Include="NewLife.UnitTest" Version="1.0.2023.1204" />
<PackageReference Include="xunit" Version="2.8.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down

0 comments on commit 0a2df92

Please sign in to comment.