问题描述
我有一个接受一个键和值的方法。这两个变量可以有一个动态的内容。
I have a method which accepts a key and a value. Both variables can have a dynamic content.
键=>是一个动态的字符串,可以是一切都像如LastSentDate结果
值=>是一个对象,它可以是一切都像如2014年10月
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"
作为重要的是像LastSentDate或任何键传递给方法,那么我想该JSON属性是价值的动态值密钥字符串,而不是字面私钥本身...
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" }"
}
如何我必须序列化,我得到所希望的输出obj的?
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 "!"§$%&/()=?"`
我使用.NET 3.5黯然
I am using .NET 3.5 sadly.
推荐答案
您可以使用 JObject
(在Newtonsoft.Json.Linq):
You could use a JObject
(in Newtonsoft.Json.Linq):
var obj = new JObject();
obj[key] = JToken.FromObject(value);
string jsonString = obj.ToString();
这篇关于串行化数据为JSON字符串动态属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!