【问题标题】:How to build anonymous types, taking the name from a variable?如何构建匿名类型,从变量中获取名称?
【发布时间】:2018-09-20 11:03:55
【问题描述】:

我想创建一个这样的自定义 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 字符串

你能帮帮我吗?

【问题讨论】:

  • 你为什么要想要匿名类型?为什么不直接创建一个类,让您的代码的用户更容易理解它的作用以及它有哪些成员?

标签: c# json anonymous-types


【解决方案1】:

为此使用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"}

【讨论】:

  • 好答案。我很沮丧,因为我是第一个,你得到了支持。无论如何:没有造成任何损害,OP得到了正确的答案:)
【解决方案2】:

你可以简单地使用一个字符串来返回那个......

public static string CreateCustomJSON(string serviceName, string value)
{
    var json = $"{{ \"{serviceName}\":\"{ value}\" }}";
    Console.WriteLine(json);
    return json;
}

除非所需的 JSON 更复杂,否则您可以使用反射

【讨论】:

  • 其实这不是一个坏主意。
  • 修复了缺少的引号,如果我不使用 $ 你会有太多的 " 像这样:"{ \""+serviceName+"\":\""+value+"\ “ }”
【解决方案3】:

也许你可以使用 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);

【讨论】:

    【解决方案4】:

    你可以使用字典

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

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      • 2018-07-30
      • 2013-12-24
      相关资源
      最近更新 更多