0

I am doing something like this

string tag_prop = "foo_bar";
string guid = "ABC";
string str = JsonConvert.SerializeObject(new { tags = new { tag_prop = guid } });

I noticed that I get the following JSON string.

{
tags : {
   tag_prop : "ABC"
        }
}

My question is how can I tell the above statement that tag_prop is actually a variable and get this

{
    tags : {
       foo_bar: "ABC"
            }
    }
3
  • What's the expected output? JSON can't contain variable references. Commented Aug 9, 2019 at 21:59
  • just updated my post Commented Aug 9, 2019 at 22:00
  • No, you can't use the value of a variable as the name of a property in an anonymous type declaration. Commented Aug 9, 2019 at 22:08

2 Answers 2

1

One way is to make tags a dictionary and use tag_prop as the parameter to the indexer. The following will give you the output you expect (with proper quoting of properties). If your situation is more complicated, you may have to adapt it futher.

string tag_prop = "foo_bar";
string guid = "ABC";
string str = JsonConvert.SerializeObject(
    new
    {
        tags = new Dictionary<string, string>
        {
            [tag_prop] = guid
        }
    }, Formatting.Indented);

The output is:

{
  "tags": {
    "foo_bar": "ABC"
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could do this:

public static ExpandoObject CreateExpandoObject(string prop, object val)
{
    dynamic expando = new ExpandoObject();
    expando = AddPropertyWithValue(expando, prop, val is null ? "" : val);
    return expando;
}

public void YourMethod() {
    string tag_prop = "foo_bar";
    string guid = "ABC";
    var dynamicPropertyObject = CreateExpandoObject(tag_prop, guid);
    string str = JsonConvert.SerializeObject(new { tags = dynamicPropertyObject });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.