#373 ObjectToKV bug

should only consider publicly readable properties
This commit is contained in:
Todd Menier 2019-01-19 11:11:17 -06:00
parent 5475393639
commit f6b335ace4
2 changed files with 42 additions and 7 deletions

View File

@ -98,6 +98,35 @@ namespace Flurl.Test
Assert.Throws<ArgumentNullException>(() => obj.ToKeyValuePairs());
}
private class ToKvMe
{
public string Read1 { get; private set; }
public string Read2 { get; private set; }
private string PrivateRead1 { get; set; } = "c";
public string PrivateRead2 { private get; set; }
public string WriteOnly {
set {
Read1 = value.Split(',')[0];
Read2 = value.Split(',')[1];
}
}
}
[Test]
public void object_to_kv_ignores_props_not_publicly_readable() {
var kv = new ToKvMe {
PrivateRead2 = "foo",
WriteOnly = "a,b"
}.ToKeyValuePairs();
CollectionAssert.AreEquivalent(new Dictionary<string, object> {
{ "Read1", "a" },
{ "Read2", "b" }
}, kv);
}
[Test]
public void SplitOnFirstOccurence_works() {
var result = "hello/how/are/you".SplitOnFirstOccurence('/');

View File

@ -16,8 +16,10 @@ namespace Flurl.Util
public static class CommonExtensions
{
/// <summary>
/// Converts an object's public properties to a collection of string-based key-value pairs. If the object happens
/// to be an IDictionary, the IDictionary's keys and values converted to strings and returned.
/// Returns a key-value-pairs representation of the object.
/// For strings, URL query string format assumed and pairs are parsed from that.
/// For objects that already implement IEnumerable&lt;KeyValuePair&gt;, the object itself is simply returned.
/// For all other objects, all publicly readable properties are extracted and returned as pairs.
/// </summary>
/// <param name="obj">The object to parse into key-value pairs</param>
/// <returns></returns>
@ -50,7 +52,7 @@ namespace Flurl.Util
}
/// <summary>
/// Splits at the first occurence of the given seperator.
/// Splits at the first occurence of the given separator.
/// </summary>
/// <param name="s">The string to split.</param>
/// <param name="separator">The separator to split on.</param>
@ -74,12 +76,16 @@ namespace Flurl.Util
private static IEnumerable<KeyValuePair<string, object>> ObjectToKV(object obj) {
#if NETSTANDARD1_0
return from prop in obj.GetType().GetRuntimeProperties()
let val = prop.GetValue(obj, null)
let getter = prop.GetMethod
where getter?.IsPublic == true
let val = getter.Invoke(obj, null)
select new KeyValuePair<string, object>(prop.Name, val);
#else
return from prop in obj.GetType().GetProperties()
let val = prop.GetValue(obj, null)
select new KeyValuePair<string, object>(prop.Name, val);
return from prop in obj.GetType().GetProperties()
let getter = prop.GetGetMethod(false)
where getter != null
let val = getter.Invoke(obj, null)
select new KeyValuePair<string, object>(prop.Name, val);
#endif
}