How to build anonymous types, taking the name from a variable?

c# anonymous type as parameter
list of anonymous type c#
return anonymous type c#
return list of anonymous type c#
c# anonymous type linq
c# anonymous type array
c# anonymous type add property
convert anonymous type to list c#

I want create a customized JSON string like this:

{"service1":"hello"}

( I simplified the example. In reality the required JSON is more complex. But to explain the problem, this example is fine )

My problem is that the service name "service1" is contained in a variable This is my code:

using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json;

    public static string CreateCustomJSON(string serviceName, object value)
    {
        var v = new { serviceName = value };
        string json = JsonConvert.SerializeObject(v);
        Console.WriteLine(json);
        return json;
    }

CreateCustomJSON("service1", "hello");
CreateCustomJSON("service2", "John");
CreateCustomJSON("service3", 13);

I got this result:

{"serviceName":"hello"}
{"serviceName":"John"}
{"serviceName":13}

because i do not know how to use Anonymous Types properly

The error is in this line:

var v = new { serviceName = value };

Or maybe there is another way to follow, to build a customized json string

Can you help me?


Use a Dictionary<string,string> for this. Json object are dictionaries after all. Try it online!

public static string CreateCustomJSON(string serviceName, string value)
{
    var v = new Dictionary<string,string> {{serviceName, value}};
    string json = JsonConvert.SerializeObject(v);
    Console.WriteLine(json);
    return json;
}

public static void Main()
{
    CreateCustomJSON("service1", "hello");
    CreateCustomJSON("service2", "John");
}

output:

{"service1":"hello"}
{"service2":"John"}

Anonymous Types, You create anonymous types by using the new operator together with an The type name cannot be specified in the variable declaration  You can't pass an anonymous type to a non generic function, unless the parameter type is object. Anonymous types are intended for short term usage within a method. From MSDN - Anonymous Types: You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type.


You can simply use a string to return that ...

public static string CreateCustomJSON(string serviceName, string value)
{
    var json = $"{{ \"{serviceName}\":\"{ value}\" }}";
    Console.WriteLine(json);
    return json;
}

Unless the required JSON is more complex then you can use reflection

Anonymous Types, Visual Basic supports anonymous types, which enable you to create objects Because the name of the data type is not specified, it is referred to as an anonymous type. Variable product is an instance of a simple anonymous type. in the anonymous type are taken from the arguments to Select , cust. Both the names and the data types of the properties in the anonymous type are taken from the arguments to Select, cust.Name and cust.ID. The properties in an anonymous type that is created by a query are always key properties. When custs3 is executed in the following For Each loop, the result is a collection of instances of an anonymous type


maybe you can use ExpandoObject. Try this if fits your needs

public static void AddPropertyToObject(ExpandoObject o, string propertyName, object propertyValue)
{
    IDictionary<string, object> d = o as IDictionary<string, object>;

    if (d == null) return;

    if (!d.ContainsKey(propertyName))
    {
                d.Add(propertyName, propertyValue);
            }
            else
            {
                d[propertyName] = propertyValue;
            }
        }

And then

dynamic eo = new ExpandoObject();
AddPropertyToObject(eo, "test", "fsdf");
string json = JsonConvert.SerializeObject(eo);

C# Anonymous Types, In C#, an anonymous type is a type (class) without any name that can The implicitly typed variable- var is used to hold the reference of anonymous types. The following example demonstrates creating an anonymous type  The implicitly typed variable - var, is used to hold the reference of an anonymous type. Anonymous type is a reference type data type and all the properties are read-only. It cannot contain methods, events, indexer or any other members. A field, property, event, indexer, or return type of a method cannot be anonymous types. The scope of an anonymous type is local to the method where it is defined.


You could use a Dictionary

var x = new Dictionary<string,string>();

x.Add ("service1", "val1");

Edit - full example
    public static string CreateCustomJSON(string serviceName, string value)
    {
        var x = new Dictionary<string, string>();
        x.Add(serviceName, value);
        return JsonConvert.SerializeObject(x);
    }

    public static void Main()
    {
        Console.WriteLine(CreateCustomJSON("service1", "hello"));
        Console.WriteLine(CreateCustomJSON("service2", "John"));
    }

Retult:

Anonymous Types In C#, Anonymous types allow us to create new types without defining them. class MyData {; public string FirstName {; get;; set;; }; public string of properties are same in terms of names and types than the compiler treats both as  Implicit types, anonymous types, and nullable value types. As stated previously, you can implicitly type a local variable (but not class members) by using the var keyword. The variable still receives a type at compile time, but the type is provided by the compiler. For more information, see Implicitly Typed Local Variables.


Pro C# 7: With .NET and .NET Core, All anonymous types automatically derive from System.Object and The ToString() implementation simply builds a string from each name-value pair. Here's an  The following example queries a collection for items of price greater than $9.99 and projects the results. The returned sequence of anonymous types is loaded into an existing table. The table schema is automatically expanded because the Book and Movies types are derived from the Item type. // Create a sequence.


Pro ASP.NET MVC 2 Framework, After compilation, the variable is just as explicitly typed as ever—the only By combining object initializers with type inference, you can construct simple data storage So, if two anonymously typed objects have the same property names and  An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle. Anonymous functions can accept inputs and return outputs, just as standard functions do. However, they can contain only a single executable statement. For example,


Initializers, Object Initializers, and Anonymous Types, And, if a class member variable is itself a reference data type, such as and a constructor that takes three parameters: an employee ID, last name, and first name. Anonymous types are useful from creating "on-the-fly" objects that we only  If the build was triggered by another build, then this variable is set to the name of the triggering build pipeline. This variable is agent-scoped. It can be used as an environment variable in a script and as a parameter in a build task, but not as part of the build number or as a version control tag.