10

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.

2 Answers 2

15

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

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

string jsonString = obj.ToString();
Sign up to request clarification or add additional context in comments.

3 Comments

After trying out some things like AddOrUpdate behavior of a JObject I must say your tip is really good it totally fitted into what I tried:
@AndrewWhitaker: Your solution is also a great approach to serialize an object with the root element included: obj[ value.GetType().Name ] = JToken.FromObject( value );
@AndrewWhitaker : Even after 8 years of your answer, you saved the day for me :)
11

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);
    ...
}

2 Comments

I am not sure whose answer is better or wether I really need the overhead of a dictionary vs solution from @Andrew Whitaker, first I have to do another SO question... :-)
Darin you rock in MVC ;-) but this point goes to Andrew. But hey you got 4 upvotes :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.