Skip to content

Commit

Permalink
add function AssertAsMap
Browse files Browse the repository at this point in the history
  • Loading branch information
liaoyustudent authored and JacksonTian committed Feb 11, 2020
1 parent 40c994f commit ac238d1
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
17 changes: 14 additions & 3 deletions csharp/core/Common.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using AlibabaCloud.TeaUtil.Utils;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace AlibabaCloud.TeaUtil
{
Expand Down Expand Up @@ -140,20 +141,30 @@ public static bool IsUnset(object obj)
return obj == null;
}

public static Dictionary<string,string> StringifyMapValue(Dictionary<string,object> dict)
public static Dictionary<string, string> StringifyMapValue(Dictionary<string, object> dict)
{
if(dict == null)
if (dict == null)
{
return null;
}

Dictionary<string, string> dictStr = new Dictionary<string, string>();
foreach(var keypair in dict)
foreach (var keypair in dict)
{
dictStr.Add(keypair.Key, keypair.Value.ToSafeString());
}

return dictStr;
}

public static Dictionary<string, object> AssertAsMap(object value)
{
if (value != null && value is JObject)
{
return (Dictionary<string, object>) ReadJsonUtil.DeserializeToDic(value);
}

throw new ArgumentException("The value is not a object");
}
}
}
16 changes: 15 additions & 1 deletion csharp/tests/CommonTest.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using AlibabaCloud.TeaUtil;

using Newtonsoft.Json.Linq;

using Xunit;

namespace tests
Expand Down Expand Up @@ -184,8 +187,19 @@ public void Test_IsUnset()
public void Test_StringifyMapValue()
{
Assert.Equal(new Dictionary<string, string>(), Common.StringifyMapValue(new Dictionary<string, object>()));
Assert.Equal("100", Common.StringifyMapValue(new Dictionary<string, object> { { "number", 100 } })["number"]);
Assert.Equal("100", Common.StringifyMapValue(new Dictionary<string, object> { { "number", 100 } }) ["number"]);
Assert.Null(Common.StringifyMapValue(null));
}

[Fact]
public void Test_AssertAsMap()
{
Assert.Throws<ArgumentException>(() => { Common.AssertAsMap(null); });
string jsonStr = "{\"arrayObj\":[[{\"itemName\":\"item\",\"itemInt\":1},{\"itemName\":\"item2\",\"itemInt\":2}],[{\"itemName\":\"item3\",\"itemInt\":3}]],\"arrayList\":[[[1,2],[3,4]],[[5,6],[7]],[]],\"listStr\":[1,2,3],\"items\":[{\"total_size\":18,\"partNumber\":1,\"tags\":[{\"aa\":\"11\"}]},{\"total_size\":20,\"partNumber\":2,\"tags\":[{\"aa\":\"22\"}]}],\"next_marker\":\"\",\"test\":{\"total_size\":19,\"partNumber\":1,\"tags\":[{\"aa\":\"11\"}]}}";
JObject obj = JObject.Parse(jsonStr);
Dictionary<string, object> dict = Common.AssertAsMap(obj);
Assert.NotNull(dict);
Assert.Equal(6, dict.Count);
}
}
}

0 comments on commit ac238d1

Please sign in to comment.