-1

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"
  }
}
Tolga Cakir
  • 725
  • 1
  • 7
  • 13

2 Answers2

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.

fbede
  • 843
  • 9
  • 12
  • Nice, but the OP is using Json.NET, not System.Text.Json – Peter Csala Jan 09 '23 at 14:11
  • I have added the Newtonsoft version, although I think the question was mainly about how to construct such an object, not about how to serialize an object generally. – fbede Jan 09 '23 at 14:16
0

Just for a record

var data = new Data();

string json = new JObject { [data.Question] = new JObject { ["Answer"] = data.Answer } }.ToString();
Serge
  • 40,935
  • 4
  • 18
  • 45