将 JsonPatchDocument 转换为字符串 C#

Convert JsonPatchDocument to string C#

我正在使用 Newtonsoft.Json.JsonConvert.SerializeObjectJsonPatchDocument<T> 转换为字符串,但 value 属性(JObject 格式)似乎没有转换为字符串.

这是它的样子:

这是我用来创建 patchDocument 对象的 JSON

[
  {
    "path": "/expenseLines/",
    "op": "ReplaceById",
    "value": {
        "ExpenseLineId": 1,
        "Amount": 4.0,
        "CurrencyAmount": 4.0,
        "CurrencyCode": "GBP",
        "ExpenseDate": "2021-11-01T00:00:00",
        "ExpenseType": "TAXI"
    }
  }
]

此 JSON 已成功反序列化为 JsonPatchDocument 对象,但是当我尝试将其序列化回 JSON 时,我丢失了 value 属性(因为如图中红色箭头所示)。 任何帮助将不胜感激:)

我无法重现你的问题,你能提供更多信息吗?我在你的第二次连载中被卡住了。但是我用了using System.Text.Json来完成你的需求,你可以看看:

型号:

public class Test
    {
        public string path { get; set; }

        public string op { get; set; }

        public TestValue testValue { get; set; } = new TestValue();
       
    }

    public class TestValue
    {

        public int ExpenseLineId { get; set; }

        public double Amount { get; set; }

        public double CurrencyAmount { get; set; }

        public string CurrencyCode { get; set; }

        public DateTime ExpenseDate { get; set; }

        public string ExpenseType { get; set; }
    }

测试控制器:

[ApiController]
    public class HomeController : Controller
    {

        [Route("test")]
        public Object Index()
        
        
        {

            var patchDocument = new Test();
            patchDocument.path = "/expenseLines/";
            patchDocument.op = "ReplaceById";
             patchDocument.testValue.ExpenseLineId = 1;
           patchDocument.testValue.Amount = 4.0;
             patchDocument.testValue.CurrencyAmount = 4.0;
           patchDocument.testValue.CurrencyCode = "GBP";
            patchDocument.testValue.ExpenseDate = DateTime.Now;
            patchDocument.testValue.ExpenseType = "TAXI";
            var options = new JsonSerializerOptions { WriteIndented = true };

           
           // var content = JsonConvert.SerializeObject(patchDocument);
           // string content1 = JsonConvert.SerializeObject(patchDocument.Operations);

            string jsonString = System.Text.Json.JsonSerializer.Serialize<Test>(patchDocument);

             string jsonString1 = System.Text.Json.JsonSerializer.Serialize(patchDocument, options);

            return jsonString;
        }

结果:

希望这对你也有帮助。