如何在C#中获取对象的键(键值) [英] How to get keys of object (key-value) in C#

查看:213
本文介绍了如何在C#中获取对象的键(键值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want get key of object, like Javasript method Object.keys. here is my object:

public object OjbectExample { get; set; }

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

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

in JS i can easy to get key of object, but in C# i don't have idea to do that.

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

i want convert it into string: "$[en|Some Value][fr|Value is here]" Any idea for this?

推荐答案

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

结果;

或者你可以像这样从JObject中获取KeysValues

Or you can take Keys and Values from JObject like this,

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

结果;

这篇关于如何在C#中获取对象的键(键值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆