Don't understand how to use JSON.NET with ASP.NET Core WebAPI

I finished my first ASP.NET Core Web API, and I would like to try using manual JSON serialization / deserialization through the JSON.NET library. In the JSON.NET documentation, they provide the following simple example of manual serialization:

public static string ToJson(this Person p)
{
    StringWriter sw = new StringWriter();
    JsonTextWriter writer = new JsonTextWriter(sw);

    writer.WriteStartObject();

    // "name" : "Jerry"
    writer.WritePropertyName("name");
    writer.WriteValue(p.Name);

    // "likes": ["Comedy", "Superman"]
    writer.WritePropertyName("likes");
    writer.WriteStartArray();
    foreach (string like in p.Likes)
    {
        writer.WriteValue(like);
    }
    writer.WriteEndArray();

    writer.WriteEndObject();

    return sw.ToString();

}

What is not enough for a beginner like myself is to use this line. For example, consider the following:

[HttpGet("/api/data")
[Produces("application/json")]
public IActionResult GetData()
{
    return Ok(new Byte[SomeBigInt]);
}

, ASP.NET Core JSON... , - . ( JSON.NET) , ? "return Ok (myJsonString)"?? - , , - ?

+4
1

Asp.Net Core , JSON. Json , :

 [HttpGet("/api/data")]
 public JsonResult GetData() {

     return Json(new {
        fieldOneString = "some value",
        fieldTwoInt= 2
     });

 }

Json() Controller JSON.NET JSON, .

:

 string jsonText = JsonConvert.SerializeObject(new {
        fieldOneString = "some value",
        fieldTwoInt= 2
     });

 Response.WriteAsync(jsonText);

: Response.WriteAsync(jsonText) using Microsoft.AspNetCore.Http Microsoft.AspNetCore.Http.Abstractions.

+1

Source: https://habr.com/ru/post/1674150/


All Articles