Add a field into JSON array - c#

I got a JSON string with an array like this:
{
"Id": 123,
"Username": "Sr. X",
"Packages": [
{
"Name": "Cups",
"SupplierId": 1,
"ProviderGroupId": 575,
"SupplierName": "Foo Cups"
},
{
"Name": "Pins",
"SupplierId": 5,
"ProviderGroupId": 1082,
"SupplierName": "Foo Pins"
}
]
}
and I want to add a new field into Packages array like:
"Packages": [
{
"Name": "Cups",
"SupplierId": 1,
"ProviderGroupId": 575,
"SupplierName": "Foo Cups",
"New Field": "Value"
},...
Right now I can add a new field but in the main object, I'm using Json.NET library to do the job, but it seems that the documentation doesn't reach that level.
Have any one of you done it before?

JObject implemets IDictionary.
var jObj = JObject.Parse(json);
foreach(var item in jObj["Packages"])
{
item["New Field"] = "Value";
}
var newjson = jObj.ToString(Newtonsoft.Json.Formatting.Indented);

Try
JObject root = (JObject) JsonConvert.DeserializeObject(File.ReadAllText("products.json"));
JArray packages = (JArray) root["Packages"];
JObject newItem = new JObject();
newItem["Name"] = "Cups";
// ...
packages.Add(newItem);
Console.WriteLine(root); // Prints new json

Related

how to replace property values in a dynamic JSON?

I'm reading my json file from and trying to replace the property values. JSON file is below.
{
"fields": {
"summary": "summaryValue",
"project": {
"key": "projectValue"
},
"priority": {
"name": "priorityValue"
},
"Requestor": {
"name": "RequestorValue"
},
"issue": {
"name": "issueValue"
},
"labels": "LabelValue",
"customfield_xyz": "customfield_xyzValue"
}
}
How can I replace the value for each item inside the fields property ?
for ex:
{"fields": {
"summary": "NewsummaryValue",
"project": {
"key": "NewprojectValue"
},
"priority": {
"name": "NewpriorityValue"
}
}
}
Below is the code to parse my json file,
StreamReader r = new StreamReader(filepath);
var jsondata = r.ReadToEnd();
var jobj = JObject.Parse(jsondata);
foreach (var item in jobj.Properties())
{
\\replace code
}
I do not know exactly what you want. But I changed the json information in the code snippet as you wanted.
dynamic dataCollection = JsonConvert.DeserializeObject<dynamic>(jsonData);
string summary = dataCollection["fields"]["summary"];
string project = dataCollection["fields"]["project"]["key"];
string priority = dataCollection["fields"]["priority"]["name"];
dynamic json = new JObject();
json.summary = summary;
json.project = project;
json.priority = priority;
dynamic jsonRoot = new JObject();
jsonRoot.fields = json;
Console.WriteLine(jsonRoot.ToString());
output:

How to create JSON object from JSON node path in C#

I want to map JSON path properties from key-value pairs to generate the JSON object in C# where the path contains nested array index path
Input:
Dictionary<string, string> properties = new Dictionary<string, string>();
properties.put("id", "1");
properties.put("name", "sample_name");
properties.put("category.id", "1");
properties.put("category.name", "sample");
properties.put("tags[0].id", "1");
properties.put("tags[0].name", "tag1");
properties.put("tags[1].id", "2");
properties.put("tags[1].name", "tag2");
properties.put("status", "available");
Output:
{
"id": 1,
"name": "sample_name",
"category": {
"id": 1,
"name": "sample"
},
"tags": [
{
"id": 1,
"name": "tag1"
},
{
"id": 2,
"name": "tag2"
}
],
"status": "available"
}
Using Jackson's JavaPropsMapper it can easily be achieved like:
JavaPropsMapper javaPropsMapper = new JavaPropsMapper();
JsonNode json = javaPropsMapper.readMapAs(properties, JsonNode.class);
How to implement this idea in C# so that I am able to generate the JSON object from the given JSON path node.
you can create anonymous object an serialize
var values = new {
id = "id",
name = "name",
category = new { id = 1, name = "sample"},
tags = new { id = 0, name = "sample" },
status = "available"
};
string json = JsonConvert.SerializeObject(values);

How to create json string from C# list of object with specific properties?

Consider I have below values in the drop-down (dropDownList variable) and user selected values are in selectedDropDownValues list.
And DB api returns the list of customers (customerDBList variable).
Now the requirement is to build JSON from selected values as mentioned below -
var dropDownList = new[] { "Customer.Id", "Customer.FirstName", "Customer.LastName", "Customer.Address.AddressLine1", "Customer.Address.AddressLine2" };
var selectedDropDownValues = new[] { "Customer.Id", "Customer.FirstName", "Customer.Address.AddressLine1" };
var customerDBList = new List<Customer>(){
new Customer {
Id=1,
FirstName="John",
LastName="Desouza",
Address=new Address{
AddressLine1="1 Street",
AddressLine2="Linking Road"
}},
new Customer {
Id=2,
FirstName="Sam",
LastName="Lewis",
Address=new Address{
AddressLine1="Fedral Highway",
AddressLine2="Louisville"
}
}};
Expected JSON output as -
[
{
"Customer": {
"Id": 1,
"FirstName": "John",
"Address": {
"AddressLine1": "1 Street"
}
}
},
{
"Customer": {
"Id": 2,
"FirstName": "Sam",
"Address": {
"AddressLine1": "Fedral Highway"
}
}
}
]
As it happens, your selectedDropDownValues strings "Customer.Address.AddressLine1" are in JSONPath syntax, so you could convert your Customer objects to an intermediate JObject then prune unwanted values using JsonExtensions.RemoveAllExcept(this JObject obj, IEnumerable<string> paths) from this answer to How to perform partial object serialization providing "paths" using Newtonsoft JSON.NET.
Note that your desired JSON has an extra level of nesting { "Customer": { ... } } not present in your data model, so it will need to be manually inserted before filtering:
var rootName = "Customer";
var query = customerDBList
// Convert to JObject
.Select(c => JObject.FromObject(c))
// Add additional level of object nesting { "Customer": { ... } }
.Select(o => new JObject( new JProperty(rootName, o)))
// Remove all but selected properties.
.Select(o => o.RemoveAllExcept(selectedDropDownValues));
var json = JsonConvert.SerializeObject(query, Formatting.Indented);
Working sample .Net fiddle here which shows the generated JSON to be, as required,
[
{
"Customer": {
"Id": 1,
"FirstName": "John",
"Address": {
"AddressLine1": "1 Street"
}
}
},
{
"Customer": {
"Id": 2,
"FirstName": "Sam",
"Address": {
"AddressLine1": "Fedral Highway"
}
}
}
]

Add new record in json

I want to add a new record to the json collection:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": 1,
"name": "Location1",
"geometry": {
"type": "Point",
"coordinates": [
150.74379,
-30.280119
]
}
},
{
"type": "Feature",
"id": 2,
"name": "Location2",
"geometry": {
"type": "Point",
"coordinates": [
148.387392,
-23.781484
]
}
}]
}
and I want to find what is the best way to create such an object and to insert it. So far I added the code below, which raises an error
Can not add Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JObject.
when I want to add the new object to the array
var array = JsonConvert.DeserializeObject<dynamic>(json);
dynamic jsonObject = new JObject(); // needs using Newtonsoft.Json.Linq;
jsonObject.type = "feature";
jsonObject.id = 3;
jsonObject.name = sAddress;
jsonObject.type = "Point";
jsonObject.coordinates = "12, 13";
array.Add(jsonObject); // error Can not add Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JObject.
The variable you call array is not an array based on the json above. The array is in the features property. You would have to do array.features.Add(jsonObject); to get your above code to work.
Like
var rootObject = JsonConvert.DeserializeObject<dynamic>(json);
dynamic feature = new JObject();
feature.type = "Feature";
feature.id = 3;
feature.name = sAddress;
dynamic geometry = new JObject();
geometry.type = "Point";
geometry.coordinates = new JArray(12, 13);
feature.geometry = geometry;
rootObject.features.Add(feature);

How can I add values to a NewtonSoft JObect?

I am usin NewtonSoft JSON.Net and I have a JObject that I need to add and remove items to and form it dynamicly from my code.
If this is my json:
{
"IgnoredInterests": [
{
"Id": 1,
"Name": "test"
},
{
"Id": 2,
"Name": "test"
}
]
}
I need to be able to add more items or even remove items from it via code.
How can I add this to the JObject:
{
"Id": 3,
"Name": "test"
}
And even remove:
{
"Id": 2,
"Name": "test"
}
I appreciate your help...
string json = #"{
'IgnoredInterests': [
{
'Id': 1,
'Name': 'test'
},
{
'Id': 2,
'Name': 'test'
}
]
}";
JObject obj = JObject.Parse(json);
string json_add = #"{
'Id': 3,
'Name': 'test'
}";
JArray array = obj.GetValue("IgnoredInterests") as JArray;
JObject obj_add = JObject.Parse(json_add);
array.Add(obj_add);
foreach (JObject item in array.Children())
{
if (item.GetValue("Id").ToString() == "2")
{
array.Remove(item);
break;
}
}

Categories