phú phạm
phú phạm

Reputation: 57

How to get keys of object (key-value) in C#

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

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

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

Upvotes: 1

Views: 27003

Answers (2)

Berkay Yaylacı
Berkay Yaylacı

Reputation: 4513

Newton is your friend,

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
}

Here is the example object;

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

Result;enter image description here

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

Result;

enter image description here

Upvotes: 3

Wowo Ot
Wowo Ot

Reputation: 1529

Create your own type

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

Then use it anywhere

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

Upvotes: 0

Related Questions