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" } }
Related
I have a JObject that I am trying to add fields to in a way like this:
JObject dataObject = new JObject();
dataObject[currentSection][key] = val;
currentSection, key and val are all strings, I want it so when its all serialized at the end that it looks something like this:
{
"currentSection": {
"key": "value"
}
}
How would I go about doing this?
You can use JObject.Add() method to add a property to JObject.
Create a JObject for the nested object.
Add property to the nested object.
Add property with nested object to root JObject.
JObject dataObject = new JObject();
JObject nestedObj = new JObject();
nestedObj.Add(key, val);
dataObject.Add(currentSection, nestedObj);
Demo # .NET Fiddle
You have one nested json object inside of the another one. So you have to create a nested currentSection json object before assigning a key to currrentSection
string currentSection = "currentSection";
string key = "key";
string val = "val";
JObject dataObject = new JObject();
dataObject[currentSection] = new JObject();
dataObject[currentSection][key] = val;
or you can do the same in one line
var dataObject = new JObject { [currentSection] = new JObject { [key] = val } };
json
var json = dataObject.ToString();
{
"currentSection": {
"key": "val"
}
}
I'm trying to find a way to add an array to a property. Currently, I'm adding non-arrys with no trouble.
var root = JObject.Parse(contractJson.ToString());
//get company name node
var companyNameMatches = root.Descendants()
.OfType<JObject>()
.Where(x => x["question"] != null && x["question"].ToString() == "Name of the company");
//add answer result to company name node
foreach (JObject jo in companyNameMatches)
{
jo.Add("answer", new JObject(new JProperty("result", Request.Form["Companyname"].ToString())));
}
So, this line...how to make "answer" into an array:
jo.Add("answer", new JObject(new JProperty("result", Request.Form["Companyname"].ToString())));
Looking for this output:
"answer":[
{
"result": "value"
}
]
You need your answer property to be an array, so you should use JArray for that. Change this line:
jo.Add("answer", new JObject(new JProperty("result", Request.Form["Companyname"].ToString())));
to:
// Create the object to put in the array
var result = new JObject(new JProperty("result", Request.Form["Companyname"].ToString()));
// Create the array as the value for the answer property
jo.Add("answer", new JArray { result });
This because you are using JObject.
use the JArray object. A JArray is a JContainer, which is a JToken, which you can add to a JObject.
for example, json of users:
string[] parameterNames = new string[] { "Test1", "Test2", "Test3" };
JArray jarrayObj = new JArray();
foreach (string parameterName in parameterNames)
{
jarrayObj.Add(parameterName);
}
string bDay = "2011-05-06";
string email = "dude#test.com";
JObject UpdateTestProfile = new JObject(
new JProperty("_delete", jarrayObj),
new JProperty("birthday", bDay),
new JProperty("email", email));
Console.WriteLine(UpdateTestProfile.ToString());
How to add JArray into JObject? I am getting an exception when changing the jarrayObj into JObject.
parameterNames = "Test1,Test2,Test3";
JArray jarrayObj = new JArray();
foreach (string parameterName in parameterNames)
{
jarrayObj.Add(parameterName);
}
JObject ObjDelParams = new JObject();
ObjDelParams["_delete"] = jarrayObj;
JObject UpdateAccProfile = new JObject(
ObjDelParams,
new JProperty("birthday", txtBday),
new JProperty("email", txtemail))
I need output in this form:
{
"_delete": ["Test1","Test2","Test3"],
"birthday":"2011-05-06",
"email":"dude#test.com"
}
I see two problems with your code as you posted it.
parameterNames needs to be an array of strings, not just a single string with commas.
You can't add a JArray directly to a JObject; you have to put it in a JProperty and add that to the JObject, just like you are doing with the "birthday" and "email" properties.
Corrected code:
string[] parameterNames = new string[] { "Test1", "Test2", "Test3" };
JArray jarrayObj = new JArray();
foreach (string parameterName in parameterNames)
{
jarrayObj.Add(parameterName);
}
string txtBday = "2011-05-06";
string txtemail = "dude#test.com";
JObject UpdateAccProfile = new JObject(
new JProperty("_delete", jarrayObj),
new JProperty("birthday", txtBday),
new JProperty("email", txtemail));
Console.WriteLine(UpdateAccProfile.ToString());
Output:
{
"_delete": [
"Test1",
"Test2",
"Test3"
],
"birthday": "2011-05-06",
"email": "dude#test.com"
}
Also, for future reference, if you are getting an exception in your code, it is helpful if you say in your question exactly what the exception is, so that we don't have to guess. It makes it easier for us to help you.
// array of animals
var animals = new[] { "cat", "dog", "monkey" };
// our profile object
var jProfile = new JObject
{
{ "birthday", "2011-05-06" },
{ "email", "dude#test.com" }
};
// Add the animals to the profile JObject
jProfile.Add("animals", JArray.FromObject(animals));
Console.Write(jProfile.ToString());
Outputs:
{
"birthday": "2011-05-06",
"email": "dude#test.com",
"animals": [
"cat",
"dog",
"monkey"
]
}
var jObject = new JObject();
jObject.Add("birthday", "2011-05-06");
jObject.Add("email", "dude#test.com");
var items = new [] { "Item1", "Item2", "Item3" };
var jSonArray = JsonConvert.SerializeObject(items);
var jArray = JArray.Parse(jSonArray);
jObject.Add("_delete", jArray);
it is easy,
JArray myarray = new JArray();
JObject myobj = new JObject();
// myobj.add(myarray); -> this is wrong. you can not add directly.
JProperty subdatalist = new JProperty("MySubData",myarray);
myobj.Add(subdata); // this is the correct way I suggest.
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));
}
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