Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

c# - Serialize data to json string with dynamic property names

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

string jsonString = obj.ToString();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...