Program Tip

C #에서 익명 유형을 키 / 값 배열로 변환합니까?

programtip 2020. 10. 20. 08:03
반응형

C #에서 익명 유형을 키 / 값 배열로 변환합니까?


다음과 같은 익명 유형이 있습니다.

new {data1 = "test1", data2 = "sam", data3 = "bob"}

이것을 받아들이고 배열 또는 사전에 키 값 쌍을 출력하는 방법이 필요합니다.

내 목표는 이것을 HttpRequest의 게시물 데이터로 사용하여 결국 다음 문자열로 연결하는 것입니다.

"data1=test1&data2=sam&data3=bob"

이 작업을 수행하려면 약간의 반성이 필요합니다.

var a = new { data1 = "test1", data2 = "sam", data3 = "bob" };
var type = a.GetType();
var props = type.GetProperties();
var pairs = props.Select(x => x.Name + "=" + x.GetValue(a, null)).ToArray();
var result = string.Join("&", pairs);

.NET 3.5 SP1 또는 .NET 4를 사용하는 RouteValueDictionary경우이를 위해 (남용) 사용할 수 있습니다 . 속성을 IDictionary<string, object>받아들이고 object키-값 쌍으로 변환 하는 생성자를 구현 하고 있습니다 .

그런 다음 쿼리 문자열을 작성하기 위해 키와 값을 반복하는 것은 간단합니다.


RouteValueDictionary에서 수행하는 방법은 다음과 같습니다.

  private void AddValues(object values)
    {
        if (values != null)
        {
            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
            {
                object obj2 = descriptor.GetValue(values);
                this.Add(descriptor.Name, obj2);
            }
        }
    }

전체 출처 : http://pastebin.com/c1gQpBMG


익명 개체를 사전으로 변환하는 기본 제공 방법이 있습니다.

HtmlHelper.AnonymousObjectToHtmlAttributes(yourObj)

또한을 반환합니다 RouteValueDictionary. 정적이라는 점에 유의하십시오.


@kbrimington의 솔루션은 멋진 확장 방법을 만듭니다-내 경우는 HtmlString을 반환합니다.

    public static System.Web.HtmlString ToHTMLAttributeString(this Object attributes)
    {
        var props = attributes.GetType().GetProperties();
        var pairs = props.Select(x => string.Format(@"{0}=""{1}""",x.Name,x.GetValue(attributes, null))).ToArray();
        return new HtmlString(string.Join(" ", pairs));
    }

Razor MVC보기에 임의의 속성을 드롭하는 데 사용하고 있습니다. RouteValueDictionary를 사용하는 코드로 시작하고 결과를 반복했지만 이것은 훨씬 깔끔합니다.


나는 다음과 같이했다.

public class ObjectDictionary : Dictionary<string, object>
{
    /// <summary>
    /// Construct.
    /// </summary>
    /// <param name="a_source">Source object.</param>
    public ObjectDictionary(object a_source)
        : base(ParseObject(a_source))
    {

    }

    /// <summary>
    /// Create a dictionary from the given object (<paramref name="a_source"/>).
    /// </summary>
    /// <param name="a_source">Source object.</param>
    /// <returns>Created dictionary.</returns>
    /// <exception cref="ArgumentNullException">Thrown if <paramref name="a_source"/> is null.</exception>
    private static IDictionary<String, Object> ParseObject(object a_source)
    {
        #region Argument Validation

        if (a_source == null)
            throw new ArgumentNullException("a_source");

        #endregion

        var type = a_source.GetType();
        var props = type.GetProperties();

        return props.ToDictionary(x => x.Name, x => x.GetValue(a_source, null));
    }
}

@GWB의를 사용하는 제안을 기반으로 RouteValueDictionary중첩 된 익명 유형을 지원하기 위해이 재귀 함수를 작성하여 중첩 된 매개 변수에 부모 키를 접두사로 붙였습니다.

public static string EncodeHtmlRequestBody(object data, string parent = null) {
    var keyValuePairs = new List<string>();
    var dict = new RouteValueDictionary(data);

    foreach (var pair in dict) {
        string key = parent == null ? pair.Key : parent + "." + pair.Key;
        var type = pair.Value.GetType();
        if (type.IsPrimitive || type == typeof(decimal) || type == typeof(string)) {
            keyValuePairs.Add(key + "=" + Uri.EscapeDataString((string)pair.Value).Replace("%20", "+"));
        } else {
            keyValuePairs.Add(EncodeHtmlRequestBody(pair.Value, key));
        }
    }

    return String.Join("&", keyValuePairs);
}

사용 예 :

var data = new {
    apiOperation = "AUTHORIZE",
    order = new {
        id = "order123",
        amount = "101.00",
        currency = "AUD"
    },
    transaction = new {
        id = "transaction123"
    },
    sourceOfFunds = new {
        type = "CARD",
        provided = new {
            card = new {
                expiry = new {
                    month = "1",
                    year = "20"
                },
                nameOnCard = "John Smith",
                number = "4444333322221111",
                securityCode = "123"
            }
        }
    }
};

string encodedData = EncodeHtmlRequestBody(data);

encodedData 된다 :

"apiOperation=AUTHORIZE&order.id=order123&order.amount=101.00&order.currency=AUD&transaction.id=transaction123&sourceOfFunds.type=CARD&sourceOfFunds.provided.card.expiry.month=1&sourceOfFunds.provided.card.expiry.year=20&sourceOfFunds.provided.card.nameOnCard=John+Smith&sourceOfFunds.provided.card.number=4444333322221111&sourceOfFunds.provided.card.securityCode=123"

이것이 비슷한 상황에있는 다른 사람에게 도움이되기를 바랍니다.

Edit: As DrewG pointed out, this doesn't support arrays. To properly implement support for arbitrarily nested arrays with anonymous types would be non-trivial, and as none of the APIs I've used have accepted arrays either (I'm not sure there's even a standardised way of serialising them with form encoding), I'll leave that to you folks if you need to support them.


using Newtonsoft.Json;
var data = new {data1 = "test1", data2 = "sam", data3 = "bob"};
var encodedData = new FormUrlEncodedContent(JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(data))

참고URL : https://stackoverflow.com/questions/3481923/in-c-sharp-convert-anonymous-type-into-key-value-array

반응형