Skip to content

Commit

Permalink
new method GetJsonValueEx
Browse files Browse the repository at this point in the history
  • Loading branch information
grandsilence committed Jul 13, 2018
1 parent 32f00c1 commit b420fd7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
20 changes: 20 additions & 0 deletions Leaf.Core.Tests/Extensions/String/StringExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,26 @@ public void GetJsonValueTest()
Assert.AreEqual("true", json.GetJsonValue("boolean"));
Assert.AreEqual("hello", json.GetJsonValue("string"));
Assert.AreEqual("world", json.GetJsonValue("endString", "\"}"));
Assert.AreEqual("world", json.GetJsonValue("endString", "\""));

Assert.IsNull(json.GetJsonValue("notFoundKey", "\"}"));
Assert.IsNull(json.GetJsonValue("notFoundKey", "\""));
}

[TestMethod]
public void GetJsonValueExTest()
{
const string json = "{\"boolean\":true,\"string\":\"hello\",\"endString\":\"world\"}";

Assert.AreEqual("true", json.GetJsonValueEx("boolean"));
Assert.AreEqual("hello", json.GetJsonValueEx("string"));
Assert.AreEqual("world", json.GetJsonValueEx("endString", "\"}"));
Assert.AreEqual("world", json.GetJsonValueEx("endString", "\""));

Assert.ThrowsException<StringBetweenException>(() => {
json.GetJsonValueEx("notFoundKey", "\"}");
json.GetJsonValueEx("notFoundKey", "\"");
});
}

[TestMethod]
Expand Down
15 changes: 14 additions & 1 deletion Leaf.Core/Extensions/String/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,20 @@ public static string ToUpperFirst(this string s, bool useToLower = true)
/// <returns>Вернет значение JSON ключа</returns>
public static string GetJsonValue(this string json, string key, string endsWith = ",\"")
{
return json.Between($"\"{key}\":", endsWith)?.Trim('"', '\r', '\n', '\t');
return endsWith != "\""
? json.Between($"\"{key}\":", endsWith)?.Trim('"', '\r', '\n', '\t')
: json.Between($"\"{key}\":\"", "\"");
}

/// <inheritdoc cref="GetJsonValue(string, string, string)"/>
/// <summary>
/// Получает из JSON значение нужного ключа и бросает исключение <exception cref="StringBetweenException" /> если ключ не был найден.
/// </summary>
/// <exception cref="StringBetweenException">Бросает если значение ключа не было найдено</exception>
public static string GetJsonValueEx(this string json, string key, string ending = ",\"")
{
return GetJsonValue(json, key, ending)
?? throw new StringBetweenException($"Не найдено значение JSON ключа \"{key}\". Ответ: {json}");
}

/// <summary>
Expand Down

0 comments on commit b420fd7

Please sign in to comment.