【问题标题】:How to get keys of object (key-value) in C#如何在 C# 中获取对象的键(键值)
【发布时间】:2020-08-22 19:56:59
【问题描述】:

我想要获取对象的键,例如 Javasript 方法 Object.keys。 这是我的对象:

public object OjbectExample { get; set; }

ObjectExample is:
{"en":"Some Value", "fr":"Value is here"}

在 JS 中我可以轻松获取对象的键,但在 C# 中我不知道这样做。

我想把它转换成字符串:“$[en|Some Value][fr|Value is here]” 有什么想法吗?

【问题讨论】:

  • ObjectExample的运行时类型是什么?
  • Newtonsoft.Json.Linq.JObject

标签: c# .net object


【解决方案1】:

Newton是你的朋友,

static void Main(string[] args)
{
     string test = "{'en':'Some Value', 'fr':'Value is here'}"; // this is your json input

     ObjectTest converted = JsonConvert.DeserializeObject<ObjectTest>(test); // deserialize json input to your custom object
}

这是示例对象;

public class ObjectTest {
     public string en { get; set; }
     public string fr { get; set; }
}

结果;

或者你可以像这样从JObjectKeysValues

static void Main(string[] args)
{
      string test = "{'en':'Some Value', 'fr':'Value is here'}"; // this is your json input

      JObject converted = JsonConvert.DeserializeObject<JObject>(test);

      if (converted != null)
      {
         Dictionary<string, string> keyValueMap = new Dictionary<string, string>();
         foreach (KeyValuePair<string, JToken> keyValuePair in converted)
         {
              keyValueMap.Add(keyValuePair.Key, keyValuePair.Value.ToString());
         }
      }
}

结果;

【讨论】:

    【解决方案2】:

    创建自己的类型

    public class OjbectExample
    {
        public string Key_ { get; set; }
        public string Value_{ get; set; }
    }
    

    然后在任何地方使用它

    ObjectExample obj = new ObjectExample(){Key_  = "en", Value_ = "Some Value"};
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 2018-09-12
      相关资源
      最近更新 更多