I have this JSON data
{
"extensions": {
"settings" : {
"extension1": {
"property1": "value 1",
"property2": "value 2"
}
}
}
}
my goal is to add a new boolean property using JSON.NET to look like this
{
"extensions": {
"settings" : {
"extension1": {
"property1": "value 1",
"property2": "value 2",
"bool_property": true
}
}
}
}
I only have this code and I'm stuck with AddAfterSelf and AddBeforeSelf
string pref = "path_of_the_preferences_file";
string _pref = string.empty;
using (StreamReader reader = new StreamReader(pref, Encoding.UTF8))
{
_pref = reader.ReadToEnd();
}
// REFORMAT JSON.DATA
JObject json = JObject.Parse(_pref);
var extension1 = json["extensions"]["settings"]["extension1"];
How do I insert the new boolean property "bool_property" ?
Thanks
A JObject is essentially a dictionary. Just get a reference to the object you wish to add the property to and add it.
var propertyName = "bool_property";
var value = true;
var obj = JObject.Parse(json);
var extension1 = obj.SelectToken("extensions.settings.extension1") as JObject;
if (extension1 != null)
{
extension1[propertyName] = value;
}
If you're targeting .NET 4 and up, you know the structure of the json and the name of the property you wish to add, you can use dynamic here.
var value = true;
dynamic obj = JObject.Parse(json);
obj.extensions.settings.extension1.bool_value = value;
You can even mix and match.
var propertyName = "bool_property";
var value = true;
dynamic obj = JObject.Parse(json);
obj.extensions.settings.extension1[propertyName] = value;
Deserialize your JSON, add a property and serialize it back into a string.
dynamic sourceJson = JsonConvert.DeserializeObject(json, typeof(object));
sourceJson.extensions.settings.extension1.bool_property = false;
var modifiedJson = JsonConvert.SerializeObject(sourceJson, Formatting.Indented);
I got it
string pref = "path_of_the_preferences_file";
string _pref = string.empty;
using (StreamReader reader = new StreamReader(pref, Encoding.UTF8))
{
_pref = reader.ReadToEnd();
}
// REFORMAT JSON.DATA
JObject json = JObject.Parse(_pref);
var extension1 = json["extensions"]["settings"]["extension1"];
var a = extension1.Children();
JProperty cond_it = null;
foreach (var b in a)
{
if (b.ToString().ToLower().Contains("cond_it"))
{
cond_it = (JProperty)b;
break;
}
}
if (cond_it != null)
{
var b = cond_it.Value.SelectToken("location").Parent;
b.AddAfterSelf(new JProperty("blacklist", true));
}
Related
JSON is holding a data.
I need to remove the node where the "id" value matches passed in value. In the below code var isRemoved = (dataDeserialized as JArray).Remove(index); is returning false. The node is not deleted. How can i delete the node?
The property name "id" is even dynamic. It will get passed in. How can i check the property name along with value (current) to find the index?
Here is what i have so far:
var entityJson = #"
[
{
'id': 1,
'code': 'abc1'
},
{
'id': 2,
'code': 'abc2'
}
]".Replace("'", "\"");
var dataDeserialized = JsonConvert.DeserializeObject<dynamic>(entityJson);// DataLoader.DeserializeJson(entityJson, false);
if(dataDeserialized.Count > 0)
{
var key = "id";
var value = "2";
var index = 0;
var isFound = false;
foreach(var d in dataDeserialized)
{
if((string)d.id == value.ToString())
{
isFound = true;
break;
}
index++;
}
if (isFound)
{
var isRemoved = (dataDeserialized as JArray).Remove(index);
if (isRemoved)
{
var setting = new JsonSerializerSettings
{
DateParseHandling = DateParseHandling.None,
};
var resul = JsonConvert.SerializeObject(dataDeserialized, setting);
//var result = JsonHelper.SerializeObject(dataDeserialized);
}
}
}
I have tried jObject as well but it is giving an error Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 2, position 13
dynamic obj = JObject.Parse(entityJson);
(obj.employees as JArray).RemoveAt(0);
Update #1: here is what worked for me for #1 above
if(dataDeserialized.Count > 0)
{
var key = "id";
var value = "2";
JArray list = new JArray();
foreach (var d in dataDeserialized)
{
if ((string)d.id != value.ToString())
{
list.Add(d);
}
}
if(list.Count > 0)
{
var result = JsonConvert.SerializeObject(list);
}
}
Still, how can i do #2, checking the "key"?
If you don't want to deserialize this json to a strongly typed object, I would recommend working with the JObject and JArray classes from the Newtonsoft.Json package because they are much more flexible for this purpose.
So you can easily remove a node from the json with a dynamic key like this:
string key = "id";
int id = 2;
var entityJson = #"
[
{
""id"": 1,
""code"": ""abc1""
},
{
""id"": 2,
""code"": ""abc2""
},
{
""id"": 3,
""code"": ""abc3""
}
]";
JArray jarray = JArray.Parse(entityJson);
var item = jarray.Children().Where(i => (int)(i as JObject).GetValue(key) == id).SingleOrDefault();
if (item != null)
{
jarray.Remove(item);
}
var resul = JsonConvert.SerializeObject(jarray);
I have to use an API that expects a string containing a an array of json objects.
internal string InitConnect( string RequestData )
{
try
{
dynamic filejsonJarray = new JArray();
filejsonJarray = JArray.Parse(RequestData);
JObject jsonObject = (JObject)filejsonJarray.First;
if (jsonObject.ContainsKey("IP_ADDRESS".ToUpper()))
{
...
}
}
}
In my code I tried different ways of calling this API but don't seem to be able to get the argument right. I have to create an object (connData) using data I have read from a config file (sJSONConfig) and use it as an argument to API; last thing I tried:
string sJSONConfig = Global.ReadJsonConfig();
// returns"{\r\n \"Name\": \"BLAH\",\r\n \"IPAddress\": \"1.2.3.4\",\r\n \"Port\": \"5880\"\r\n}"
JArray filejsonJarray = new JArray();
JObject jsonObject = new JObject();
jsonObject = JObject.Parse(sSJONConfig);
//filejsonJarray = JArray.Parse(sSJONConfig);
//jsonObject = (JObject)filejsonJarray.First;
// Reconnect using new config data
var connData = new
{
NAME = jsonObject.Property("Name").Value.ToString(),
IP_ADDRESS = jsonObject.Property("IPAddress").Value.ToString(),
PORT = jsonObject.Property("Port").Value.ToString(),
Enabled = "true",
Something = "false"
};
string reqData = JsonConvert.SerializeObject(filejsonJarray);
//filejsonJarray.Add(reqData);
InitConnect(reqData);
Obviously, I cannot changed the InitConnect API.
You can create your desired JSON like this:
string sJSONConfig = Global.ReadJsonConfig();
JObject jsonObject = JObject.Parse(sJSONConfig);
JObject connData = new JObject(
new JProperty("NAME", jsonObject["Name"]),
new JProperty("IP_ADDRESS", jsonObject["IPAddress"]),
new JProperty("PORT", jsonObject["Port"]),
new JProperty("Enabled", "true"),
new JProperty("Something", "false")
);
JArray filejsonJarray = new JArray(connData);
string reqData = filejsonJarray.ToString();
InitConnect(reqData);
I am trying to make a json object like this with JObject:
{
"input": {
"webpage/url": "http://google.com/"
}
}
I can add properties like:
JObject job = new JObject(
new JProperty("website/url", "http://www.google.com") );
But any time I try to nest an object inside another object so I can have the parent "input" it throws an exception.
How do you make nested properties with JObject?
Probably the most straightforward way would be:
var input = new JObject();
input.Add("webpage/url", "http://google.com");
var obj = new JObject();
obj.Add("input", input);
Which gives you:
{
"input": {
"webpage/url": "http://google.com"
}
}
Another way would be:
var input = new JObject
{
{ "webpage/url", "http://google.com" }
};
var obj = new JObject
{
{ "input", input }
};
... Or if you wanted it all in one statement:
var obj = new JObject
{
{
"input",
new JObject
{
{ "webpage/url", "http://google.com" }
}
}
};
Just carry on as you are, and nest them in another level:
JObject job = new JObject(
new JProperty("website/url", "http://www.google.com") );
JObject parent = new JObject(new JProperty("input", job));
parent.ToString() now gives:
{ "input": {
"website/url": "http://www.google.com" } }
I have a JSON string like this:
{
"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".
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.
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();
Another way, with minimal property retrieving:
var val = voicgObj["value"] as JObject;
JProperty optionProp = val.Property("option");
string option = optionProp.Value.Value<string>();
if (option == "ML")
optionProp.Value = "Male";
else if (option == "FM")
optionProp.Value = "Female";
I need to create a Json object dynamically by looping through columns.
so declaring an empty json object then add elements to it dynamically.
eg:
List<String> columns = new List<String>{"FirstName","LastName"};
var jsonObj = new {};
for(Int32 i=0;i<columns.Count();i++)
jsonObj[col[i]]="Json" + i;
And the final json object should be like this:
jsonObj={FirstName="Json0", LastName="Json1"};
[TestFixture]
public class DynamicJson
{
[Test]
public void Test()
{
dynamic flexible = new ExpandoObject();
flexible.Int = 3;
flexible.String = "hi";
var dictionary = (IDictionary<string, object>)flexible;
dictionary.Add("Bool", false);
var serialized = JsonConvert.SerializeObject(dictionary); // {"Int":3,"String":"hi","Bool":false}
}
}
I found a solution very similar to DPeden, though there is no need to use the IDictionary, you can pass directly from an ExpandoObject to a JSON convert:
dynamic foo = new ExpandoObject();
foo.Bar = "something";
foo.Test = true;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
and the output becomes:
{ "FirstName":"John", "LastName":"Doe", "Active":true }
You should use the JavaScriptSerializer. That can Serialize actual types for you into JSON :)
Reference: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
EDIT: Something like this?
var columns = new Dictionary<string, string>
{
{ "FirstName", "Mathew"},
{ "Surname", "Thompson"},
{ "Gender", "Male"},
{ "SerializeMe", "GoOnThen"}
};
var jsSerializer = new JavaScriptSerializer();
var serialized = jsSerializer.Serialize(columns);
Output:
{"FirstName":"Mathew","Surname":"Thompson","Gender":"Male","SerializeMe":"GoOnThen"}
Using dynamic and JObject
dynamic product = new JObject();
product.ProductName = "Elbow Grease";
product.Enabled = true;
product.StockCount = 9000;
Console.WriteLine(product.ToString());
// {
// "ProductName": "Elbow Grease",
// "Enabled": true,
// "StockCount": 9000
// }
Or how about:
JObject obj = JObject.FromObject(new
{
ProductName = "Elbow Grease",
Enabled = true,
StockCount = 9000
});
Console.WriteLine(obj.ToString());
// {
// "ProductName": "Elbow Grease",
// "Enabled": true,
// "StockCount": 9000
// }
https://www.newtonsoft.com/json/help/html/CreateJsonDynamic.htm