-1

I am trying to create a JSON string content by passing a double typed value (named time). My JSON content is also containing a root header object (named UserAddTime). I would like to add time in Minutes object.

double time = 60;
var content = new StringContent
        (@"{
            'UserAddTime':
            {
                'Minutes':"+time+",
                'TotalPrice':0.00,
                'IsTaxIncluded':false
            }
          }",
        Encoding.UTF8, "application/json"); 

It doesn't allow me to add time like this:

'Minutes':"+time+",

And shows me the red line error content LOC:

enter image description here

I am trying this solution, but not able to get my expected results like:

{
    "UserAddTime" : {
        "Minutes" : 60,
        "TotalPrice" : 0.00,
        "IsTaxIncluded" : false
    }
}

Your any help will be really appreciated!

3
  • Instead of StringContent you can narrow down to a JsonContent type, working directly with models and using factory method JsonContent.Create. Commented May 19, 2024 at 12:05
  • 1
    The correct thing todo is in the answer. YOu get the error here because after concatenation time you concatenate a new standard string. You can't simply have a line break in such a string. For example put a @ in front of that string just like you did for the first string here before the time variable. Then your compiler error should go but its still bad code ;) Use what's in the answer. Commented May 19, 2024 at 12:13
  • @Ralf That's not working. Commented May 19, 2024 at 12:26

1 Answer 1

3

Instead of constructing the JSON manually, you should look for constructing an object and then serialize via JSON library such as System.Text.Json or Newtonsoft.Json.

using System.Text.Json;

double time = 60;
var body = new 
{
    UserAddTime = new
    {
        Minutes = time,
        TotalPrice = 0.00,
        IsTaxIncluded = false
    }
};

var content = new StringContent(JsonSerializer.Serialize(body),
    Encoding.UTF8, "application/json");
Sign up to request clarification or add additional context in comments.

2 Comments

Does it create a root header object?
@SoftSol Try and see yourself.

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.