How do you Add or Update a JProperty Value in a JObject

后端 未结 2 1259
一个人的身影
一个人的身影 2020-12-06 04:51

I am currently using the following extension method to perform this task, but it almost seems like there should be some existing included method or extension to perform this

相关标签:
2条回答
  • 2020-12-06 05:07

    Anyone trying to access nested JSON use the approach as in answer by @pjs adding extra braces as required.

    JObject item = JObject.Parse("{
       "test": {
           "first": "one",
           "second": "two",
           "nth":   "n"
       }
    }");
    

    To edit:

    item["test"]["nth"] = "updated";
    

    Updates the JObject to:

    {
       "test": {
           "first": "one",
           "second": "two",
           "nth":   "updated"
       }
    }
    
    0 讨论(0)
  • 2020-12-06 05:18

    as @dbc described in the comment, you can simply use the indexer to make this happen.

    var item = JObject.Parse("{ 'str1': 'test1' }");
    
    item["str1"] = "test2";
    item["str3"] = "test3";
    

    see the fiddle for more details

    0 讨论(0)
提交回复
热议问题