繁体   English   中英

将 JsonPatchDocument 转换为字符串 C#

[英]Convert JsonPatchDocument to string C#

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

这是它的样子: jsonconvert_doesnot_convert_value_to_json

这是我用来创建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;
        }

结果:

在此处输入图片说明

希望这对你也有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM