如何更新使用NewtonSoft一个JSON对象的属性 [英] How to update a property of a JSON object using NewtonSoft

查看:257
本文介绍了如何更新使用NewtonSoft一个JSON对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a JSON string like this:

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

我想更新选项属性如果值为ML 如果值为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");



我不知道怎么去的选项的孩子。

在此先感谢。

推荐答案

您可以通过使用属性键访问对象

You can access the object by using properties as keys:

JObject code = JObject.Parse(json);
string gender = (string)code["value"]["option"];

有关你的榜样,请尝试:

For your example, try:

JObject code = JObject.Parse(json);
var val = code["value"];
string option = (string)val["option"];

if (option == "ML")
   val["option"] = "Male";

if (option == "FM")
   val["option"] = "Female";

string result = code.ToString();

这篇关于如何更新使用NewtonSoft一个JSON对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆