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.