簡體   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