C # 7 Tuple json support

I want to get my C # 7 tuple property names in my JSON issue (Newtonsoft.Json). My problem: When I want to convert my tuple to JSON format that doesn't support my parameter names.

For example, this is my method "Test2" and you can see the JSON output:

public void Test2()
{
    var data = GetMe2("ok");
    var jsondata = JsonConvert.SerializeObject(data);//JSON output is {"Item1":5,"Item2":"ok ali"}
}

public (int MyValue, string Name) GetMe2(string name)
{
    return (5, name + " ali");
}

      

The JSON output is "{" Item1 ": 5," Item2 ":" ok ali "}" but I want "{" MyValue ": 5," Name ":" ok ali "}";

This is not impossible, because I can get the property names at runtime:

foreach (var item in this.GetType().GetMethods())
{
    dynamic attribs = item.ReturnTypeCustomAttributes;
    if (attribs.CustomAttributes != null && attribs.CustomAttributes.Count > 0)
    {
        foreach (var at in attribs.CustomAttributes)
        {
            if (at is System.Reflection.CustomAttributeData)
            {
                var ng = ((System.Reflection.CustomAttributeData)at).ConstructorArguments;
                foreach (var ca in ng)
                {
                    foreach (var val in (IEnumerable<System.Reflection.CustomAttributeTypedArgument>)ca.Value)
                    {
                        var PropertyNameName = val.Value;
                        Console.WriteLine(PropertyNameName);//here is property names of C#7 tuple
                    }
                }
            }
        }
        dynamic data = attribs.CustomAttributes[0];
        var data2 = data.ConstructorArguments;
    }

}

      

+3


source to share


2 answers


For a specific case, this is not possible here. This is because it SerializeObject

has no way of knowing where the tuple came from, all it sees is ValueTuple<int, string>

.



The situation would be different if you were serializing an object with tuple attributes, in which case you SerializeObject

can use reflection to find the attributes TupleElementNames

(although this is currently not the case).

+2


source


The short answer is that tuples have no properties.

A tuple is a bag of values ​​used primarily to return multiple values ​​from a method.

They were never designed to model objects.



The only way to solve your problem, if you don't want to create a type for that, is:

public void Test2()
{
    var data = GetMe2("ok");
    var jsondata = JsonConvert.SerializeObject(new { data.MyValue, data.Name });//JSON output is {"Item1":5,"Item2":"ok ali"}
}

      

+2


source







All Articles