Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize data to json string with dynamic property names

Tags:

c#

json.net

I have a method which accepts a key and a value. Both variables can have a dynamic content.

key => is a dynamic string which can be everything like e.g. "LastSentDate"
value => is an object which can be everything like e.g. "2014-10-10"

As key is a dynamic value like "LastSentDate" or whatever key is passed to the method then I want that the json property is the value of the key string and not literally key itself...

public void SetRowVariable(string key, object value)
{
    var obj = new { key = value }; // key property is literally taken maybe anonym object is not a good idea?
     string jsonString = JsonConvert.SerializeObject(obj);

    // jsonString should have that output => "{ "LastSentDate": "2014-10-10" }"
}

How do I have to serialize the obj that I get the wished output?

It must also be possible that the "key" property can contain special chars like "!"§$%&/()=?"`

I am using .NET 3.5 sadly.

like image 541
Pascal Avatar asked Nov 11 '14 20:11

Pascal


2 Answers

You could use a JObject (in Newtonsoft.Json.Linq):

var obj = new JObject();
obj[key] = JToken.FromObject(value);

string jsonString = obj.ToString();
like image 53
Andrew Whitaker Avatar answered Nov 15 '22 20:11

Andrew Whitaker


You may try using a Dictionary<string, object>:

public void SetRowVariable(string key, object value)
{
    var obj = new Dictionary<string, object>();
    obj[key] = value; // Of course you can put whatever crap you want here as long as your keys are unique
    string jsonString = JsonConvert.SerializeObject(obj);
    ...
}
like image 21
Darin Dimitrov Avatar answered Nov 15 '22 20:11

Darin Dimitrov