Home > Net >  Send a String as JSON object from web api to the client
Send a String as JSON object from web api to the client

Time:01-26

In my .Net Core (EF) WebApi in C# I have an object Property that contains a (string) property Settings.

var p = new Property(){ Settings = "{decimals: 2, color: 'red'}" }

As you can see, the string is not in a strict JSON format, so parsing on the client asks additional energy, I would like to spend on the server side.

How should I configure that property that the EF returns me not a string, but a json object, so, for the example above that would be the object like this:

{ 
  settings: {
    decimals: 2, 
    color: 'red'
  } 
}

and not

{ 
  settings: "{decimals: 2, color: 'red' }"
}

that I obtain actually...

CodePudding user response:

Try to put the keys in quotation marks as well:

var p = new Property(){ Settings = "{'decimals': 2, 'color': 'red'}" }

Or maybe try to parse the string to a json object.

CodePudding user response:

I would use the JObject class to create a JSON object out of it. Have a look here for more details about the class.

CodePudding user response:

You could try something like this:

[HttpGet]
public IActionResult YourApiEndpoint()
{
    var p = new Property() { Settings = "{decimals: 2, color: 'red'}" };
    var settings = JsonConvert.DeserializeObject<Settings>(p.Settings);
    return Ok(new
    {
        Settings = settings
    });
}

public class Settings
{
    public int Decimals { get; set; }
    public string Color { get; set; }
}

or in case you want to use the built-in serializer, use JsonSerializer.Deserialize<> instead of JsonConvert

  •  Tags:  
  • Related