如何使用NewtonSoft更新JSON对象的属性?

时间:2021-07-31 02:23:54

I have a JSON string like this:

我有一个这样的JSON字符串:

{
    "code": "GENDER",
    "value": { "option": "ML" }
}

I would like to update the option property to "Male" if the value is "ML" and "Female" if the value is "FM".

我想将选项属性更新为“Male”(如果值是“ML”),“Female”(如果值是“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");

I don't know how to get to the option which is a child of value.

我不知道如何得到一个有价值的子选项。

Thanks in advance. Any pointers would be great.

提前谢谢。任何指针都很好。

1 个解决方案

#1


32  

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();

#1


32  

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();