Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

c#

json.net

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 (or at least a subset of this). If there isn't anything within Json.NET then what is the recommended process, or how would I change the code below to be closer to the recommended process.

public static partial class ExtensionMethods {     public static JObject SetPropertyContent(this JObject source, string name, object content)     {         var prop = source.Property(name);          if (prop == null)         {             prop = new JProperty(name, content);              source.Add(prop);         }         else         {             prop.Value = JContainer.FromObject(content);         }          return source;     } } 

I can confirm the above code works for basic usage, but I'm not certain how well it holds up to broader usage.

The reason I have this extension returning a JObject is so that you would be able to chain calls (either multiple calls to this extension or to other methods and extensions).

i.e.,

var data = JObject.Parse("{ 'str1': 'test1' }");  data     .SetPropertyContent("str1", "test2")     .SetPropertyContent("str3", "test3");  // { //   "str1": "test2", //   "str3": "test3" // } 
like image 368
pjs Avatar asked May 06 '15 19:05

pjs


People also ask

How do you value a JObject?

The simplest way to get a value from LINQ to JSON is to use the Item[Object] index on JObject/JArray and then cast the returned JValue to the type you want. JObject/JArray can also be queried using LINQ.

How do you iterate over a JObject?

If you look at the documentation for JObject , you will see that it implements IEnumerable<KeyValuePair<string, JToken>> . So, you can iterate over it simply using a foreach : foreach (var x in obj) { string name = x. Key; JToken value = x.

What is JProperty C#?

Represents a JSON property. Newtonsoft.Json.Linq. JToken.

How do I access my property from JObject?

C# - How to get a property from a JSON string without parsing it to a class using SelectToken and JObject. Using JObject we can get the address using SelectToken: var data = (JObject)JsonConvert. DeserializeObject(myJsonString); var address = data.


1 Answers

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

like image 116
pjs Avatar answered Oct 11 '22 18:10

pjs