I have a long tree json document, here is the part of it
"childs": [
{
"id": "id1",
"name": "name1",
"childs": []
},
{
"id": "id2",
"name": "name21",
"childs": [
{
"id": "id3",
"name": "name123124",
"childs": [
{
"id": "id4",
"name": "namewe1231",
"childs": [
{
"id": "id5",
"name": "name123123",
"childs": [
{
"id": "id5",
`
i need to save all id from this document for local storage like:
id1
id2
id3
id4 etc...
is it even possible? JObject and dynamic variable didnt help me.
heres code i've been trying to compile but it returned me just first id from tree
`
string source = File.ReadAllText(jsonModelPath);
dynamic data = JObject.Parse(source);
File.WriteAllText(path, data.id);
`
you can try something like this
string[] ids = JObject.Parse(json)
.Descendants()
.OfType<JProperty>()
.Where(a => a.Name == "id")
.Select(a => a.Value.ToString())
.ToArray();
or you can put all ids in one line
string strIds = string.Join(" ",ids);
or each id in the new line
string strIds = string.Join("\n",ids);
and save
File.WriteAllText(path, strIds);
Related
I'm new to C#, and I'm updating to mess with lists.
I currently have this event Object.
From it, I need to generate a new String list.
I must remove all emails that are on Data3 and that are on Data1 and Data2.
{
"event":
{
"userData": [
{
"Data1": [
{
"comentario": "",
"email": "erick#gmail.com",
"name": "erick"
},
{
"comentario": "",
"email": "isa#gmail.com",
"name": "isa"
}
],
"Data2": [
{
"comentario": "",
"email": "erick#gmail.com",
"name": "erick"
}
],
"Data3": [
{
"comentario": "",
"email": "erick#gmail.com",
"name": "erick"
},
{
"comentario": "",
"email": "joseph#gmail.com",
"name": "joseph"
},
{
"comentario": "",
"email": "ju#gmail.com",
"name": "ju"
},
{
"comentario": "",
"email": "isa#gmail.com",
"name": "isa"
}
]
}
]
}
}
The end result would be this:
Newlist = ["joseph#gmail.com", "ju#gmail.com"]
As "erick#gmail.com" and "isa#gmail.com" are in Data1 and Data2, I should remove both from Data3, and return only the others.
If you want to exclude elements from a list that are found in another list just use
var result= list1.Except(list2);
You can use Enumerable.Except method as mentioned in previous answer. A complete example is given below:
List<String> list1 = new List<string>();
list1.Add("Apple");
list1.Add("Ball");
list1.Add("Car");
List<String> list2 = new List<string>();
list2.Add("Cat");
list2.Add("Dog");
list2.Add("Mouse");
list2.Add("Ball");
List<String> newList = list2.Except(list1).ToList();//don't forget to parse new list
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
I'm regex searching a {keyword} against a field [Name] from one of the collections [Brands] of Mongo DB using C#. And the result items would be sorted by the textMatchScore by descending. The result looks good but the format looks pretty weird.
The expected results would be like this.
[
{
"id": "5c8bcbc36ad6840725182158",
"name": "Window XP",
"dateAdded": "2019-03-15T15:58:58.925Z"
},
{
"id": "5c8bcbc96ad6840725182159",
"name": "Wind",
"dateAdded": "2019-03-15T15:59:05.429Z"
},
{
"id": "5c8bcbd16ad684072518215a",
"name": "Wired",
"dateAdded": "2019-03-15T15:59:13.292Z"
}
]
This is the actual result though.
[
[
{
"name": "_id",
"value": "5c8bcbc36ad6840725182158"
},
{
"name": "Name",
"value": "Window XP"
},
{
"name": "DateAdded",
"value": "2019-03-15T15:58:58.925Z"
},
{
"name": "textMatchScore",
"value": 0
}
],
[
{
"name": "_id",
"value": "5c8bcbc96ad6840725182159"
},
{
"name": "Name",
"value": "Wind"
},
{
"name": "DateAdded",
"value": "2019-03-15T15:59:05.429Z"
},
{
"name": "textMatchScore",
"value": 0
}
]
]
This is the C# part code.
[HttpGet]
public async Task<IActionResult> QueryAsync([FromQuery]string q, [FromQuery]int limit = 10, [FromQuery]int skip = 0)
{
var mongoUrl = new MongoUrl(_mongoConfig.ConnectionString);
var client = new MongoClient(mongoUrl);
var database = client.GetDatabase(mongoUrl.DatabaseName);
var collection = database.GetCollection<Brand>("Brands");
var regex = new BsonRegularExpression($".*{q}.*","i");
var filter = Builders<Brand>.Filter.Regex("Name", regex);
var projection = Builders<Brand>.Projection.MetaTextScore("textMatchScore");
var sort = Builders<Brand>.Sort.MetaTextScore("textMatchScore");
var result = await collection.Find(filter).Project(projection).Sort(sort).Skip(skip).Limit(limit).ToListAsync();
return Ok(result);
}
Has the query been implemented right? And, what can I do to make the result format a pretty tidy json format?
I have a json file as such:
{
"rowId": "39",
"refNumber": "19",
"title": "Mobile",
"date": "10/29/2015",
"status": "saved"
}{
"rowId": "10",
"refNumber": "478",
"title": "Completion",
"date": "10/30/2015",
"status": "saved"
}{
"rowId": "11",
"refNumber": "604",
"title": "Online Order",
"date": "10/30/2015",
"status": "failed"
}
What I'd like to do is query the json file in c# like as such with a winforms app:
string qrySaved = "select count(*) as total from file where status = 'saved'";
string qryFailed = "select count(*) as total from file where status = 'failed'";
Then place the results in two variables.
I did the following:
logFolder = Directory.GetCurrentDirectory();
logFolder = logFolder.Replace("\\bin\\Debug", "\\metrics");
logFile = logFolder + #"\log.json";
I'm using the Newtonsoft.Json nuget resource and know how to read the first object but can't figure out how to query the file to return total counts based on a given element.
You can try something like this:
static void Main(string[] args)
{
string json = File.ReadAllText("sample1.json");
var array = JArray.Parse(json);
int savedcount = array.Count(i => i["status"].Value<string>() == "saved");
int failedcount = array.Count(i => i["status"].Value<string>() == "failed");
}
Might a typo but the JSON posted was invalid so I changed it as below to make it work:
[
{
"rowId": "39",
"refNumber": "19",
"title": "Mobile",
"date": "10/29/2015",
"status": "saved"
},
{
"rowId": "10",
"refNumber": "478",
"title": "Completion",
"date": "10/30/2015",
"status": "saved"
},
{
"rowId": "11",
"refNumber": "604",
"title": "Online Order",
"date": "10/30/2015",
"status": "failed"
}
]
I have a table like (array of arrays) object in json format that I would like to convert to a collection of c# objects.
{
"Columns": [
{
"id": 1,
"name": "column name 1",
"other stuff": "blah blah"
},
{
"id": 2,
"name": "column name 2",
"other stuff": "blah blah"
},
{
"id": 3,
"name": "column name 3",
"other stuff": "blah blah"
}
],
"Data": [
[
"blah bla",
"bloop",
1
],
[
"t",
"another random value",
5
],
[
"foo",
"bar",
5
],
[
"something valuable",
"value2",
5
]
]
}
I would like to serialize that into a collection of objects or data table similar to the following:
public class Row
{
public string ColumnName1 {get;set;}
public string ColumnName2 {get;set;}
public int ColumnName3 {get;set;}
}
var jsonString = "same as above just properly escaped";
list<Row> rows = Deserialize(jsonString);
The column mappings would be consistent based on the order of the values.
Edit:
I would love to have the data in a more c# friendly way similar to this example:
{
"Data": [
{
"column name 1": "blah bla"
},
{
"column name 1": "T"
},
{
"column name 1": "blahbla"
}
]
}
But I don't have control over that so...
You can use Json.Net's LINQ-to-JSON API to parse the JSON data into the format that you want:
JObject jo = JObject.Parse(json);
List<Row> rows = jo["Data"]
.Children<JArray>()
.Select(ja => new Row
{
ColumnName1 = (string)ja[0],
ColumnName2 = (string)ja[1],
ColumnName3 = (int)ja[2]
})
.ToList();
Fiddle: https://dotnetfiddle.net/bA9vSH