本文介紹了如何使用 NewtonSoft 更新 JSON 對象的屬性的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個這樣的 JSON 字符串:
I have a JSON string like this:
{
"code": "GENDER",
"value": { "option": "ML" }
}
如果值為 "ML"
和 "Female",我想將
option
屬性更新為 "Male"
如果值為 "FM"
.
I would like to update the option
property to "Male"
if the value is "ML"
and "Female"
if the value is "FM"
.
我已經到了這一點,但不確定如何繼續:
I have got to this point, but am unsure how to proceed:
JArray contentobject = (JArray)JsonConvert.DeserializeObject(contentJSON);
JObject voicgObj = contentobject.Children().FirstOrDefault(ce => ce["code"].ToString() == "GENDER") as JObject;
JProperty voicgProp = voicgObj.Property("value");
我不知道如何訪問 option
,它是 value
的子項.
I don't know how to get to the option
which is a child of value
.
提前致謝.任何指針都會很棒.
Thanks in advance. Any pointers would be great.
推薦答案
可以通過屬性作為鍵來訪問對象:
You can access the object by using properties as keys:
JObject obj = JObject.Parse(json);
string gender = (string)obj["value"]["option"];
對于您的示例,請嘗試:
For your example, try:
JObject obj = JObject.Parse(json);
var val = obj["value"];
string option = (string)val["option"];
if (option == "ML")
val["option"] = "Male";
if (option == "FM")
val["option"] = "Female";
string result = obj.ToString();
這篇關于如何使用 NewtonSoft 更新 JSON 對象的屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!