Home > Blockchain >  Convert JsonPatchDocument to string C#
Convert JsonPatchDocument to string C#

Time:11-05

I am using Newtonsoft.Json.JsonConvert.SerializeObject to convert a JsonPatchDocument<T> to string but it's value property (which is in JObject format) doesn't seem to be converted to string.

Here is what it looks like: jsonconvert_doesnot_convert_value_to_json

Here is the JSON I am using to create patchDocument object

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

This JSON is successfully deserialized to JsonPatchDocument object but when I try to serialize it back to JSON, I lose value property (as shown in the picture by red arrows). Any help would be appreciated :)

CodePudding user response:

I can't reproduce your problem, can you provide more information? I got stuck during your second serialization. But I used using System.Text.Json to complete your needs, you can look at:

Model:

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; }
    }

TestController:

[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;
        }

Result:

enter image description here

Hope this helps you too.

  • Related