skip to Main Content

How to serialize an object to json through setting json field name from object’s property value?

I am using NewtonsoftJson as a json library.

public class Data
{
  public string Question {get;set;} = "Test Question?";
  public string Answer {get;set;} = "5";
}

expected json output:

{
  "Test Question?": {
    "Answer": "5"
  }
}

2

Answers


  1. You can use a dictionary for that:

    JsonSerializer.Serialize(
        new Dictionary<string, object>
        {
            {
                data.Question, new
                {
                    data.Answer
                }
            }
        });
    

    or if you are using Newtonsoft, you can use the
    JsonConvert.SerializeObject method for serialization, with the same input.

    Login or Signup to reply.
  2. Just for a record

    var data = new Data();
    
    string json = new JObject { [data.Question] = new JObject { ["Answer"] = data.Answer } }.ToString();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search