is it possible to add a value to existing json object?
My example code:
var obj = new { Vall = "myVal1", Val2 = "myVal2", Val3 = "myVal3" };
this is what I'm trying to do:
obj.AddValue(Val4, "myVal4");
is it possible to add a value to existing json object?
My example code:
var obj = new { Vall = "myVal1", Val2 = "myVal2", Val3 = "myVal3" };
this is what I'm trying to do:
obj.AddValue(Val4, "myVal4");
var obj = new { Vall = "myVal1", Val2 = "myVal2", Val3 = "myVal3" };
is not JSON, despite the similarity. That is a compiler-generated "anonymous type", which means the compiler creates a type for you with three string
properties named Val1
, Val
and Val3
. Other than the fact that you can't speak the name of the type (it is anonymous), it is a pretty normal .NET class. No, you can't add extra properties to a class at runtime.
The closest thing to what you want might be ExpandoObject
, but to be honest it sounds like you're trying to do something peculiar.
As everybody else pointed out, you are dealing with anonymous types
here, not with JSON objects. Unfortunately, they are autogenerated types in compiled code and this mean they cannot be altered as you wish.
A simple workaround would be declaring a new anonymous type that can store an additional field and setting the values of the common fields to the ones of the old object as follows:
var obj_old = new { Vall = "myVal1", Val2 = "myVal2", Val3 = "myVal3" };
var obj_new = new { Vall = obj_old.Vall, Val2 = obj_old.Val2, Val3 = obj_old.Val3, Val4 = "myVal4" };
Alternatively, declare the object with an additional field whose value can be set when needed:
var obj = new { Vall = "myVal1", Val2 = "myVal2", Val3 = "myVal3", Val4 = String.Empty };
// ...
obj.Val4 = "myVal4";
Properties of anonymous types in C# is read-only, you can clone this object and add your property using Json.Net
like this:
var obj = new { ID = 1234, Name = "FooBar" };
obj = JObject.FromObject(obj).Add("feeClass", "A");
Final Json:
{
"ID": 1234,
"Name": "FooBar",
"feeClass": "A"
}