我要创建一个自定义的JSON字符串,如下所示:
{"service1":"hello"}
(我简化了示例。实际上,所需的JSON更复杂。 但是为了说明问题,这个例子很好)
我的问题是服务名称“ service1”包含在变量中 这是我的代码:
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);
我得到了这个结果:
{"serviceName":"hello"}
{"serviceName":"John"}
{"serviceName":13}
因为我不知道如何正确使用匿名类型
此行中的错误:
var v = new { serviceName = value };
或者也许还有另一种方法可以遵循, 构建自定义的json字符串
你能帮我吗?
答案 0 :(得分:4)
为此使用Dictionary<string,string>
。 Json对象毕竟是字典。 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");
}
输出:
{"service1":"hello"}
{"service2":"John"}
答案 1 :(得分:2)
您可以简单地使用字符串将其返回...
public static string CreateCustomJSON(string serviceName, string value)
{
var json = $"{{ \"{serviceName}\":\"{ value}\" }}";
Console.WriteLine(json);
return json;
}
除非所需的JSON更复杂,否则您可以使用反射
答案 2 :(得分:0)
您可以使用字典
var x = new Dictionary<string,string>();
x.Add ("service1", "val1");
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"));
}
致敬:
答案 3 :(得分:0)
也许您可以使用ExpandoObject。如果您需要,请尝试
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;
}
}
然后
dynamic eo = new ExpandoObject();
AddPropertyToObject(eo, "test", "fsdf");
string json = JsonConvert.SerializeObject(eo);