How can I add values to a NewtonSoft JObect? - c#

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;
}
}

Related

How to get all value of particular key in JSON?

I have a JSON structure that contains different levels. How to iterate the JSON and get all values of a particular key in JSON in C#
Below is my JSON file
{
"name": "EPM Company",
"id": "kpfwzgmhpm",
"type": "root",
"childern": [
{
"cid": "67",
"cname": "cname1",
"childern": [
{
"reading": [
{
"id": 121,
"name": "test1"
},
{
"id": 1121,
"name": "test11"
}
]
}
]
},
{
"cid": "454",
"cname": "cname14",
"childern": [
{
"reading": [
{
"id": 454,
"name": "test14"
},
{
"id": 21,
"name": "test141"
}
]
}
]
}
]
}
This is the JSON format. I am trying to get the value in the below format.
{
"name": "EPM Company",
"id": "kpfwzgmhpm",
"value": [
{
"id": 121,
"name": "test1",
"cid": "67",
"cname": "cname1"
},
{
"id": 1121,
"name": "test11",
"cid": "67",
"cname": "cname1"
},
{
"id": 124234,
"cname": "test12342",
"cid": "67",
"name": "cname1"
},
{
"id": 454,
"name": "test14",
"cid": "454",
"cname": "cname14"
},
{
"id": 21,
"name": "test141",
"cid": "454",
"cname": "cname14"
},
{
"id": 121,
"name": "test123122",
"cid": "454",
"cname": "cname14"
}
]
}
fetching all the reading key and its value-added to array with its cid and came. is it possible?
advanced thanks for the help
my code in c# is
public string SensorList(string entireData)
{
if (string.IsNullOrEmpty(entireData))
{
return string.Empty;
}
var returnObj = new Jobject ();
JObject o = JObject.Parse(entireData);
var childern = o["children"];
returnObj.Add("name" = o ["name"];
returnObj.Add("id" = o ["id"];
returnObj.Add("value" = o ["value"];
var valuearry = new JArray();
foreach(var data in childern)
{
foreach(var reading in data["reading"])
{
var valobj = new Jobject ();
valobj.Add( "cid",data["id"])
valobj.Add( "cname",data["name"])
valobj.Add( "name",reading["id"])
valobj.Add( "id",reading["name"])
valuearry.add()
if(data.containsKey("children"))
{
var sensorInfo = SensorList(data["children"]);
}
}
returnObj.Add("value",valuearry);
// var output = sensorInfo.SelectMany(x => ((JObject)x).Properties().Select(y => new JObject {
// new JProperty("id",y.Name),
// new JProperty("name",y.Value["name"])
// })).ToList();
// var returnArray = new JArray(output);
return returnObj.ToString();
}
}
recurring part is not working and take too much time for other long JSON file

Get JSON child element value

I'm trying to get spuCode from this JSON:
{
"msg": "success",
"state": 0,
"data": {
"result": {
"spuCode": "541426110605",
"productName": "纯黑色斜纹面料铅笔裤百搭大码小脚裤弹力打底裤休闲裤子女",
"productTitle": null,
"spuImgs": [
"https://cbu01.alicdn.com/img/ibank/2016/276/468/3618864672_1742354982.jpg",
"https://cbu01.alicdn.com/img/ibank/2016/793/372/3617273397_1742354982.jpg",
"https://cbu01.alicdn.com/img/ibank/2016/726/552/3617255627_1742354982.jpg",
"https://cbu01.alicdn.com/img/ibank/2017/521/101/4624101125_1742354982.jpg",
"https://cbu01.alicdn.com/img/ibank/2017/070/749/4580947070_1742354982.jpg"
],
"upAndDown": 1,
"updateTime": 1537096913958,
"platform": "ALIBABA",
"skus": [
{
"skuCode": "3488434133172",
"sellPrice": 3900,
"sellableNum": 905,
"productProps": [
{
"propId": 7590793702270582000,
"valueId": 5453504708925905000,
"propName": "颜色",
"valueName": "纯黑色(相同面料)"
},
{
"propId": 9000005669393888000,
"valueId": 6217370164147047000,
"propName": "尺码",
"valueName": "XXL"
}
],
As you can see there is Parent data with child result so I added this code:
string sp = "";
var obj = Newtonsoft.Json.Linq.JObject.Parse(responseFromServer);
foreach (JObject child in obj["data"]["result"].OfType<JObject>())
{
sp = child["spuCode"].ToString();
MessageBox.Show(sp);
}
But it never triggers MessageBox.Show what am I missing here?
result isn't an array so there is no need for foreach.
Try SelectToken method like this:
var spuCode = (string)obj.SelectToken("data.result.spuCode");

Add a field into JSON array

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

JSON Enum list deserialization

I have JSON Like below
{
"_id": "0FEB6D4B-8DA5-4143-B926-11A7AE4F3B12",
"device": {
"name": "test",
"family": "test"
},
"channels": [
{
"mcl": 33,
"vtype": "FLOAT",
"category": " Current"
},
{
"tag": "OperationMode",
"vtype": "BYTE",
"enums": [
{
"0": "Off"
},
{
"1": "On"
},
{
"2": "ByPass"
}
]
}
]
}
I am using Json.net to deserialize the JSON to C# object. I am not able to manage to convert the enum list. I validated if this is valid JSON. I tried with custom converter & string converter but reader value is null. Any quick help appreciated.
JObject jR = JObject.Parse(YourJsonString);
JArray oR = (JArray)jR["channels"];
JArray jA = (JArray)oR[1]["enums"];
foreach (var item in jA)
{
Dictionary<string,string> enums = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,string>>(item.ToString());
foreach (var en in enums)
{
Console.WriteLine(en.Value);
}
}
Fiddler: https://dotnetfiddle.net/ziSep1

Parse json data string store in array

Below is parsed json data which is of type string.
"data": [
{
"Company": {
"id": "1",
“Value": “20”,
"companyId": "2001”,
}
},
{
"Company": {
"id": "2",
“value”: "20”,
"companyId”: "2002”,
}
},
{
"Company": {
"id": “3”,
“value”: “30”,
"companyId”: "2003”,
}
},
]
var parseData = Newtonsoft.Json.Linq.JObject.Parse (e.ResponseData.ToString ());
Convert json data string store in array, Arraylist of stored Company Value.
this is first time dealing with Json object string.
string json = #"{
'status_code': 200,
'status_text': 'matches found',
'data': [{
'company': {
'id': '1',
'value': '20',
'companyId': '2001',}
},
{
'company': {
'id': '2',
'value': '20',
'companyId': '2002',}
},
{
'company': {
'id': '3',
'value': '30',
'companyId': '2003',}
},]
}";
JObject jObj = JObject.Parse(json);
var ids = jObj["data"].Children()["company"]["companyId"];
var list = new List<string>();
list.AddRange(ids.Select(id => id.Value<string>()));
foreach (var item in list)
Console.WriteLine(item);
// Outputs ->
// 2001
// 2002
// 2003
Edit:
"Everything" from companies as a list:
JObject jObj = JObject.Parse(json);
var jEnum = jObj["data"].Children()["company"];
var list = jEnum.Select(company =>
company.Values().Select(current =>
current.Value<string>()).ToList()).ToList();

Categories