|
| 1 | +using ServiceStack.Text; |
| 2 | +using System; |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Linq; |
| 5 | + |
| 6 | +namespace ServiceStack.Redis |
| 7 | +{ |
| 8 | + public static class RedisDataInfoExtensions |
| 9 | + { |
| 10 | + public static String ToJsonInfo(this RedisText redisText) |
| 11 | + { |
| 12 | + var source = redisText.GetResult(); |
| 13 | + return Parse(source); |
| 14 | + } |
| 15 | + |
| 16 | + #region Private |
| 17 | + |
| 18 | + private static String Parse(String source) |
| 19 | + { |
| 20 | + var result = new Dictionary<String, Dictionary<String, String>>(); |
| 21 | + var section = new Dictionary<String, String>(); |
| 22 | + |
| 23 | + var rows = SplitRows(source); |
| 24 | + |
| 25 | + foreach (var row in rows) |
| 26 | + { |
| 27 | + if (row.IndexOf("#", StringComparison.Ordinal) == 0) |
| 28 | + { |
| 29 | + var name = ParseSection(row); |
| 30 | + section = new Dictionary<String, String>(); |
| 31 | + result.Add(name, section); |
| 32 | + } |
| 33 | + else |
| 34 | + { |
| 35 | + var pair = ParseKeyValue(row); |
| 36 | + if (pair.HasValue) |
| 37 | + { |
| 38 | + section.Add(pair.Value.Key, pair.Value.Value); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return JsonSerializer.SerializeToString(result); |
| 44 | + } |
| 45 | + |
| 46 | + private static IEnumerable<String> SplitRows(String source) |
| 47 | + { |
| 48 | + return source.Split(new[] { "\r\n" }, StringSplitOptions.None).Where(n => !String.IsNullOrWhiteSpace(n)); |
| 49 | + } |
| 50 | + |
| 51 | + private static String ParseSection(String source) |
| 52 | + { |
| 53 | + return (source.IndexOf("#", StringComparison.Ordinal) == 0) |
| 54 | + ? source.Trim('#').Trim() |
| 55 | + : String.Empty; |
| 56 | + } |
| 57 | + |
| 58 | + private static KeyValuePair<String, String>? ParseKeyValue(String source) |
| 59 | + { |
| 60 | + KeyValuePair<String, String>? result = null; |
| 61 | + |
| 62 | + var devider = source.IndexOf(":", StringComparison.Ordinal); |
| 63 | + if (devider > 0) |
| 64 | + { |
| 65 | + var name = source.Substring(0, devider); |
| 66 | + var value = source.Substring(devider + 1); |
| 67 | + result = new KeyValuePair<String, String>(name.Trim(), value.Trim()); |
| 68 | + } |
| 69 | + |
| 70 | + return result; |
| 71 | + } |
| 72 | + |
| 73 | + #endregion Private |
| 74 | + } |
| 75 | +} |
0 commit comments