![](/img/trans.png)
[英]How to get actual value from object of JsonPatchDocument in C#?
[英]Convert JsonPatchDocument to string C#
我正在使用Newtonsoft.Json.JsonConvert.SerializeObject
將JsonPatchDocument<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;
}
結果:
希望這對你也有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.