Home > Software design >  Construction JSON value dynamically in C#
Construction JSON value dynamically in C#

Time:02-20

My below code works fine if I repace my "temp" with any other hard-coded string value. But I am not sure How can I pass the temp value each time in the JSON I am creating. How can I fix this? I need to have my json something like {"device1": 24, "device2": 25, "device3": 26}

for (int i = 1; i <= numOfEvents; i  )
            {
                string temp = (i   23).ToString();
                dynamic foo = JObject.FromObject(new { Hello = "{ \"device\" : temp }" });
           

CodePudding user response:

better to use a string builder

    var numOfEvents = 3;
    StringBuilder sb= new ();
    for (int i = 1; i <= numOfEvents; i  )
    {
        string temp = (i   23).ToString();
         sb.Append( $",\"device{i}\" : {temp}");
    }
    var json=sb.ToString();
    json="{"  json.Substring(1)  "}";
    
    var foo= JObject.Parse(json);

result

{"device1" : 24,"device2" : 25,"device3" : 26}

or

json="{ \"Hello\": {"  json.Substring(1)  "}}";

or if you want to use JObject

    var numOfEvents = 3;
    JObject jo = new JObject();
    for (int i = 1; i <= numOfEvents; i  )
        jo.Add("device"   i.ToString(), i   23);

    JObject jsonObject = new JObject();
    jsonObject["Hello"] = jo;

result

{ "Hello": {"device1" : 24,"device2" : 25,"device3" : 26}}
  • Related