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

Viewed 263

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?

4 Answers

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"}

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

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:

enter image description here

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);
Related