0

The JsonSerializer I am using is System.Text.Json; in .net core 3.1

Here are two projects, one is project A, the other is project B.

Here is the code of project A:

namespace WebApplication1.Controllers
{
    [Route("api/")]
    public class TestController : Controller
    {            
        [HttpGet]
        [Route("Get")]
        public async Task<string> Get()
        {
            Models.TestModel TestModel = new Models.TestModel() { Success = "1" };            
            string Content = JsonSerializer.Serialize(TestModel, typeof(Models.TestModel), new JsonSerializerOptions() { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(System.Text.Unicode.UnicodeRanges.All) });            
            return Content;
        }                      
    }
}

And here is the code of project B:

namespace WebApplication2
{
    [Route("api/")]
    public class TestController : Controller
    {
        private readonly IHttpClientFactory _clientFactory;
        public TestController(IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
        }
        [HttpGet]
        [Route("TestGet")]
        public async Task TestGet()
        {
            var request = new HttpRequestMessage(HttpMethod.Get,
                string.Format("https://localhost:44345/api/Get"));

            var client = _clientFactory.CreateClient();
            client.Timeout = TimeSpan.FromSeconds(5);
            var response = await client.SendAsync(request);
            string Content = "";
            if (response.IsSuccessStatusCode)
            {
                Content = await response.Content.ReadAsStringAsync();
                Models.TestModel TestModel = new Models.TestModel();
                TestModel = (Models.TestModel)JsonSerializer.Deserialize(Content, typeof(Models.TestModel));
            }
        }
    }
}

Both of them using the same model:

public class TestModel
    {
        public string Success { get; set; } = "";
        public string SuccessRemark { get; set; } = "";
    }

Now the problem is the project A will always produce JSON contains by strangely character '\'.

For example, the right JSON is

{"Success":"1","SuccessRemark":""}

And it will be turn out to be this:

"{\"Success\":\"1\",\"SuccessRemark\":\"\"}"

This strange character '\' makes project B can not be deserialized rightly.

I have considered by using a replacing method to remove the character '\'.

I followed all the answers in Replacing backslash in a string to remove the character '\'. Meanwhile, none works.

I knew another way to produce json without strangely character '\':

        [Produces("application/json")]
        [HttpGet]
        [Route("Get")]
        public async Task<Models.TestModel> Get()
        {
            Models.TestModel TestModel = new Models.TestModel() { Success = "1" };            
            return TestModel;
        }   

Well, in this way only can return a static model while:

I need to return a success model if all codes run successfully.

I need to return an error model if code runs with an error.

This way can not solve this.

Would you please help me? Thank you.

dbc
  • 104,963
  • 20
  • 228
  • 340
Melon NG
  • 2,568
  • 6
  • 27
  • 52
  • 2
    isn’t that because you are returning a string where you should return JSON? Your first class correctly returns a string which would escape the “, make sure it returns proper JSON if thats what you want by returning a JObject for example – Matt Douhan Feb 06 '20 at 06:50
  • @MattDouhan I always consider JSON and string is the same thing while now I am not sure about this. – Melon NG Feb 06 '20 at 06:56
  • 1
    A string that contains JSON will need to be **escaped**. So the backslashes are correct. You should return an object, which ASP.NET should convert to JSON for you. – Rowan Freeman Feb 06 '20 at 06:58
  • Very similar to [JSON.NET Parser *seems* to be double serializing my objects](https://stackoverflow.com/q/25559179/3744182) - you are returning a serialized JSON string, which in turn gets serialized as a JSON string literal a second time. Return the actual model instead. – dbc Feb 07 '20 at 17:35

1 Answers1

1

Try this

try
        {
            if (success)
                return Json(new TestModel() { Success = "1" });
            else
                return Json(new TestModel() { Success = "0", SuccessRemark = "error" });
        }
        catch (Exception ex)
        {
            return Json(new TestModel() { Success = "0", SuccessRemark = ex.Message });
        }
Asherguru
  • 1,687
  • 1
  • 5
  • 10