Getting Json object to individual items in c# using linq - c#

var respnse1 = client.GetAsync(hostmi).Result;
string content1 = respnse1.Content.ReadAsStringAsync().Result;
JObject joResponse = JObject.Parse(content1);
JObject ojObject = (JObject)joResponse["usermachine"];
JArray array = (JArray)joResponse["pInterval"];
var pLNo= (from p in array select ["pLocationNumber"]).ToList();
var pLIny= (from p in array select p["pLocationInterval"]).ToList();
// The following is not working
Usermachine um = new Usermachine();
um.employeeid = (string) ojObject["usermachine"]["employeeid"];
um.employeename = (string)ojObject["usermachine"]["employeename"];
I am getting an error at the um.employeeid = … which is system null exception.
I tried to see the content of ojObject in the immediate window as follows:
? ojObject
{
"employeeid": "1123",
"employeename": "EMP 001 NAME",
"mMacID": "E0138",
"machinename": "FOS",
"iscleaning": 1,
"isperforming": 1,
"isverifying": 1,
"cSeqno": 1,
"cMacID": "E0138",
"cInterval": 112,
"cCleanOperationMaxTime": 300,
"cPerformOperationMaxTime": 600,
"oSequenceID": 6,
"oMacID": "E0138",
"oItemNumber": " ",
"oBatchNumber": " ",
"oPONumber": " ",
"oCompletedOperation": 0,
"oComplOperStartTime": 0,
"oCompOperEndndTime": 0,
"oOperationToContinue": 1
}
base: {
"employeeid": "1123",
"employeename": "EMP 001 NAME",
"mMacID": "E0138",
"machinename": "FOS",
"iscleaning": 1,
"isperforming": 1,
"isverifying": 1,
"cSeqno": 1,
"cMacID": "E0138",
"cInterval": 112,
"cCleanOperationMaxTime": 300,
"cPerformOperationMaxTime": 600,
"oSequenceID": 6,
"oMacID": "E0138",
"oItemNumber": " ",
"oBatchNumber": " ",
"oPONumber": " ",
"oCompletedOperation": 0,
"oComplOperStartTime": 0,
"oCompOperEndndTime": 0,
"oOperationToContinue": 1
}
Type: Object
My objective is to get the employeeid and employeename if possible using a select (linq) query else even the above approach is OK if it works.

Ok, I got it working using Linq. As reference pasting the code below
var respnse1 = client.GetAsync(hostmi).Result;
string content1 = respnse1.Content.ReadAsStringAsync().Result;
JObject joResponse = JObject.Parse(content1);
JObject ojObject = (JObject)joResponse["usermachine"];
JArray array = (JArray)joResponse["pInterval"];
The Json string is as follows :
{
"usermachine": {
"employeeid": "1123",
"employeename": "EMP 001 NAME"
},
"pInterval": [
{
"pMachineID": "E0138",
"pmachinetoLocationSequence": 1
},
{
"pMachineID": "E0138",
"pmachinetoLocationSequence": 2
},
{
"pMachineID": "E0138",
"pmachinetoLocationSequence": 3
}
]
}
(I tried my best in formatting and pasting. Hope it sticks, still learning!!)
You will find that there is an array (pInterval ) as in master / detail relationship tables.
Now to get the master data code as follows:
string employeeid = (string) ojObject.SelectToken("employeeid");
string employeename = (string) ojObject.SelectToken("employeename");
Now to get the details data as follows
var pmachinetoLocationSequence= (from p in arrayselect p["pmachinetoLocationSequence"]).ToList();
foreach (var item in pmachinetoLocationSequence)
{
Console.WriteLine(item.Value<string>().ToString());
}
Is there a way to get multiple fields in the above var pmachinetoLocationSequence line ?

Related

How to generate treeview using Linq

I have the following three tables,
Region Table,
RegionId
RegionName
1
Admin
2
North Region
3
South Region
Branch Table
BranchId
BranchName
FkRegionId
1
Roswell Rd
3
2
Test
2
3
Piedmont Ave
2
4
Ashford Dunwoody
1
User Table
UserId
FirstName
FkBranchId
1
Hasa
9
2
Jane
1
3
Joyce
7
4
Jane
1
5
John
3
6
Sharon
8
As mentioned above, each branch has its region and each user has a branch. I need to create following JSON for my frond-end usage. Therefore I need to populate data in order to create this JSON.
Region1
Branch1
Jane
Paul
Alex
Branch2
Neil
Kaja
Alex
Region2
Branch4
Ama
Hema
Ira
Branch5
Laura
Tim
Yea
How can I do this using C# and linq?
You need to use Linq Join and GroupBy as following:
var regions = new List<Region>()
{
new Region() { RegionId = 1, RegionName = "Admin" },
new Region() { RegionId = 2, RegionName = "North Region" },
new Region() { RegionId = 3, RegionName = "South Region" }
};
var branchs = new List<Branch>()
{
new Branch() {BranchId = 1, BranchName = "Roswell Rd", FkRegionId = 3},
new Branch() {BranchId = 2, BranchName = "Test", FkRegionId = 2},
new Branch() {BranchId = 3, BranchName = "Piedmont Ave ", FkRegionId = 2},
new Branch() {BranchId = 4, BranchName = "Ashford Dunwoody ", FkRegionId = 1},
};
var users = new List<User>()
{
new User() {UserId = 1, FirstName = "Hasa", FkBranchId = 9},
new User() {UserId = 2, FirstName = "Jane", FkBranchId = 1},
new User() {UserId = 3, FirstName = "Joyce", FkBranchId = 7},
new User() {UserId = 4, FirstName = "Jane", FkBranchId = 1},
new User() {UserId = 5, FirstName = "John", FkBranchId = 3},
new User() {UserId = 6, FirstName = "Sharon", FkBranchId = 8},
};
var tree = from user in users
join branch in branchs on user.FkBranchId equals branch.BranchId
join region in regions on branch.FkRegionId equals region.RegionId
group region by new { region.RegionId, branch.BranchId } into grp
select new
{
RegionName = regions.FirstOrDefault(s => s.RegionId == grp.Key.RegionId).RegionName,
Branchs = new
{
BranchName = branchs.FirstOrDefault(s => s.FkRegionId == grp.Key.RegionId).BranchName,
Users = users.Where(i => i.FkBranchId == grp.Key.BranchId).Select(s => new
{
FirstName = s.FirstName
})
}
};
var json = JsonConvert.SerializeObject(tree, Formatting.Indented);
This will give you an expected result:
[
{
"RegionName": "South Region",
"Branchs": {
"BranchName": "Roswell Rd",
"Users": [
{
"FirstName": "Jane"
},
{
"FirstName": "Jane"
}
]
}
},
{
"RegionName": "North Region",
"Branchs": {
"BranchName": "Test",
"Users": [
{
"FirstName": "John"
}
]
}
}
]
var jsonResponse = "[{\"UserId\":195,\"FirstName\":\"Carlton\",\"BranchId\":4,\"BranchName\":\"Test\",\"RegionId\":1,\"RegionName\":\"Admin\"},{\"UserId\":223,\"FirstName\":\"Lorenza\",\"BranchId\":4,\"BranchName\":\"Test\",\"RegionId\":1,\"RegionName\":\"Admin\"},{\"UserId\":163,\"FirstName\":\"Alice\",\"BranchId\":17,\"BranchName\":\"Ratnapura\",\"RegionId\":1,\"RegionName\":\"Admin\"},{\"UserId\":264,\"FirstName\":\"Karen\",\"BranchId\":7,\"BranchName\":\"Peachtree\",\"RegionId\":3,\"RegionName\":\"South Region\"},{\"UserId\":266,\"FirstName\":\"Starla\",\"BranchId\":7,\"BranchName\":\"Peachtree\",\"RegionId\":3,\"RegionName\":\"South Region\"},{\"UserId\":30,\"FirstName\":\"Jane\",\"BranchId\":9,\"BranchName\":\"Henderson Mill\",\"RegionId\":3,\"RegionName\":\"South Region\"}]";
var myDeserializedClass = JsonConvert.DeserializeObject < List < Root >> (jsonResponse);
var jsonResponseList = myDeserializedClass.GroupBy(item = >item.RegionId).Select(grp = >grp.GroupBy(item = >item.BranchId)).Select(grp = >grp.Select(innerg = >innerg.GroupBy(item = >item.UserId))).ToList();
var serializer = JsonConvert.SerializeObject(jsonResponseList, Formatting.Indented);
Root class
public class Root
{
public int UserId { get; set; }
public string FirstName { get; set; }
public int BranchId { get; set; }
public string BranchName { get; set; }
public int RegionId { get; set; }
public string RegionName { get; set; }
}
and the output:
[
[
[
[
{
"UserId": 195,
"FirstName": "Carlton",
"BranchId": 4,
"BranchName": "Test",
"RegionId": 1,
"RegionName": "Admin"
}
],
[
{
"UserId": 223,
"FirstName": "Lorenza",
"BranchId": 4,
"BranchName": "Test",
"RegionId": 1,
"RegionName": "Admin"
}
]
],
[
[
{
"UserId": 163,
"FirstName": "Alice",
"BranchId": 17,
"BranchName": "Ratnapura",
"RegionId": 1,
"RegionName": "Admin"
}
]
]
],
[
[
[
{
"UserId": 264,
"FirstName": "Karen",
"BranchId": 7,
"BranchName": "Peachtree",
"RegionId": 3,
"RegionName": "South Region"
}
],
[
{
"UserId": 266,
"FirstName": "Starla",
"BranchId": 7,
"BranchName": "Peachtree",
"RegionId": 3,
"RegionName": "South Region"
}
]
],
[
[
{
"UserId": 30,
"FirstName": "Jane",
"BranchId": 9,
"BranchName": "Henderson Mill",
"RegionId": 3,
"RegionName": "South Region"
}
]
]
]
]
If these are physically related tables then EF has taken care of it already. Just make sure your lazy loading is ON or you can eager load data as well by using include and then display data as it is. If you want to eager load information then try this query
using(var db = new DBContext){
var result = db.region.include(x => x.branches).theninclude(x => x.users).toList();
}
result will contain all of your data then bind that data into your custom define DTOs or you can directly bind entity models into views.
Its an overview of the code you can have your own implementation.
If there is no physical relations in between tables then use join using linq here is the link you can follow how joins works in linq.
link

merging two json result into one and adding the Key inside array?

I've merged two JSON response into a single object:
This is how I did it
string peter= "\"peter\"";
string james= "\"james\"";
var jsonStringJames = await jsonStringJames .Content.ReadAsStringAsync();
var jsonStringPeter = await responsePeter.Content.ReadAsStringAsync();
return Ok("{" + peter+ ":" + jsonStringPeter + ","+ james+ ":" + jsonStringJames + "}");
my JSON looks as follow:
{
"peter": {
"total": 1,
"result": [
{
"value": "James Bond",
"OWNER":"peter" <--- add this
}
]
},
"james": {
"count": 2,
"next": null,
"previous": null,
"results": [{
"gender": "male"
"OWNER":"james" <--- add this
}]
}
}
How do I add the object name as a key? server-side?
Thanks alot!
try this using ´JObject´
var jsonStringPeter = await responsePeter.Content.ReadAsStringAsync();
var objJson = JObject.Parse(jsonStringPeter);
objJson["result"][0]["OWNER"] = "peter";
var jsonStringJames = await jsonStringJames.Content.ReadAsStringAsync();
var objJson2 = JObject.Parse(jsonStringJames);
objJson2["OWNER"] = "james";

Extract all values from data in JSON

I have a json response with multiple movie titles in "data". Is there a way to quickly extract them? I need an array with just movie titles.
{
"page": "2",
"per_page": 10,
"total": 13,
"total_pages": 2,
"data": [{
"Poster": "N/A",
"Title": "They Call Me Spiderman",
"Type": "movie",
"Year": 2016,
"imdbID": "tt5861236"
}, {
"Poster": "N/A",
"Title": "The Death of Spiderman",
"Type": "movie",
"Year": 2015,
"imdbID": "tt5921428"
}, {
"Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw##._V1_SX300.jpg",
"Title": "Spiderman in Cannes",
"Type": "movie",
"Year": 2016,
"imdbID": "tt5978586"
}]
}
You can use:
newtonsoft.
C# System.dynamic.
C# ExpandoObject Class.
In this way:
dynamic content = JsonConvert.DeserializeObject<ExpandoObject>(data);
Something like this:
using System;
using System.Dynamic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string data = #"{
'page': '2',
'per_page': 10,
'total': 13,
'total_pages': 2,
'data': [{
'Poster': 'N/A',
'Title': 'They Call Me Spiderman',
'Type': 'movie',
'Year': 2016,
'imdbID': 'tt5861236'
}, {
'Poster': 'N/A',
'Title': 'The Death of Spiderman',
'Type': 'movie',
'Year': 2015,
'imdbID': 'tt5921428'
}, {
'Poster': 'https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw##._V1_SX300.jpg',
'Title': 'Spiderman in Cannes',
'Type': 'movie',
'Year': 2016,
'imdbID': 'tt5978586'
}]
}";
dynamic content = JsonConvert.DeserializeObject<ExpandoObject>(data);
int i;
int len = content.data.Count;
string result = "";
string[] myArray;
for (i = 0; i < len; i++)
{
result += content.data[i].Title; // Extract the movie title.
result += ","; // Conact with commas.
}
result = result.Substring(0, result.Length - 1);
myArray = result.Split(','); // Array of string with the movie titles.
Console.WriteLine(myArray[0]);
}
}
See in action: .NET Fiddle.
var data = new Dictionary<string, string>();
data.Add("foo", "baa");
JavaScriptSerializer ser = new JavaScriptSerializer();
var JSONString = ser.Serialize(data); //JSON encoded
var JSONObj = ser.Deserialize<Dictionary<string, string>>(JSONString); //JSON decoded
Console.Write(JSONObj["foo"]); //prints: baa
using Newtonsoft.Json.Linq might do the simplest work for you.
using Newtonsoft.Json.Linq;
List<string> movieTitles = (JObject.Parse(json)["data"]).
Cast<JToken>().Select(x => x["Title"].ToString()).ToList();

Delete JSON Data inside Property based on ID in C#

I have a requirement to delete the data inside JSON file. I have tried so many way but it is not deleting the data. I have also tried this example.
Remove JSON objects from a large file
But in above example they are passing a jsonstring but I have a jobject type of data.
My JSON File is as following.
{
"id": 123,
"name": "Pankaj Kumar",
"address": {
"street": "El Camino Real",
"city": "San Jose",
"zipcode": 95014
},
"experiences": [
{
"companyid": 1,
"companyname": "abc1"
},
{
"companyid": 20,
"companyname": "Genpact Headstrong"
},
{
"companyid": 71,
"companyname": "new company"
},
{
"companyid": 77,
"companyname": "Mind Tree LTD"
},
{
"companyid": 89,
"companyname": "TCS"
},
{
"companyid": 22,
"companyname": "Hello World LTD"
}
],
"phoneNumber": 9988664422,
"role": "Developer"
}
I want to delete company based on companyid.
I have tried following code to delete based on company id.
private void DeleteCompany() {
var json = File.ReadAllText(jsonFile);
try {
var jObject = JObject.Parse(json);
JArray experiencesArrary = (JArray) jObject["experiences"];
Console.Write("Enter Company ID to Delete Company : ");
var companyId = Convert.ToInt32(Console.ReadLine());
if (companyId > 0) {
var companyName = string.Empty;
foreach(var company in experiencesArrary.Where(obj => obj["companyid"].Value < int > () == companyId)) {
companyName = Convert.ToString(company["companyname"]);
}
var companyToDeleted = "{ 'id': " + companyId + ", 'companyname': '" + companyName + "'}";
experiencesArrary.Remove(companyToDeleted);
jObject["experiences"] = experiencesArrary;
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(jsonFile, output);
} else {
Console.Write("Invalid Company ID, Try Again!");
UpdateCompany();
}
} catch (Exception) {
throw;
}
}
Please suggest or modify my code which delete the data.
There is no need for creating deleteObject like you are doing, you are very close to solution.You can simply find your object like this and remove.
var companyToDeleted = experiencesArrary.Where(obj => obj["companyid"].Value<int>() == companyId).ToList();
foreach (var item in companyToDeleted)
{
experiencesArrary.Remove(item);
}
Update
var companyToDeleted = experiencesArrary.FirstOrDefault(obj => obj["companyid"].Value<int>() == companyId);
experiencesArrary.Remove(companyToDeleted);

How to iterate through JSON array from n1ql query?

so I'm using couchbase queue to Enqueue my beacon information. I'm trying to use n1ql query for my get method and I'm having trouble getting all the information. I realized I'm only getting the first beacon entry because result.Rows returns one element, an array of BeaconInfoN1ql. I wanted to iterate through that array and add each to a list.
try {
var cluster = new Cluster(new ClientConfiguration());
using (var bucket = cluster.OpenBucket("BeaconInfoN1ql"))
{
string query = "SELECT * FROM `BeaconInfoN1ql`";
var queryRequest = new QueryRequest(query);
var result = bucket.Query<dynamic>(queryRequest);
foreach (var row in result.Rows)
{
int i = 0;
var beacon = new Beacon()
{
SerialNumber = row.BeaconInfoN1ql[i].serialNumber,
ReceivedDate = Convert.ToDateTime(row.BeaconInfoN1ql[i].receivedDate),
ReceiverId = row.BeaconInfoN1ql[i].receiverId,
Distance = Convert.ToDouble(row.BeaconInfoN1ql[i].distance),
Rssi = Convert.ToInt32(row.BeaconInfoN1ql[i].rssi),
NewDistance = Convert.ToDouble(row.BeaconInfoN1ql[i].newDistance),
DistanceTesting = Convert.ToDouble(row.BeaconInfoN1ql[i].distanceTesting),
};
i++;
_beaconsList.Add(beacon);
}
}
return _beaconsList;
my result.Rows looks like this
result.Rows=
{{
"BeaconInfoN1ql": [
{
"distance": 2.2705747109792007,
"distanceTesting": 22,
"newDistance": 22,
"receivedDate": "0001-01-01T00:00:00",
"receiverId": "42008780c4b9b329",
"rssi": -73,
"serialNumber": "888"
},
{
"distance": 2.2705747109792007,
"distanceTesting": 22,
"newDistance": 22,
"receivedDate": "0001-01-01T00:00:00",
"receiverId": "42008780c4b9b329",
"rssi": -73,
"serialNumber": "888"
},
{
"distance": 2.2705747109792007,
"distanceTesting": 22,
"newDistance": 22,
"receivedDate": "0001-01-01T00:00:00",
"receiverId": "42008780c4b9b329",
"rssi": -73,
"serialNumber": "888"
},
{
"distance": 2.2705747109792007,
"distanceTesting": 22,
"newDistance": 22,
"receivedDate": "0001-01-01T00:00:00",
"receiverId": "42008780c4b9b329",
"rssi": -73,
"serialNumber": "888"
},
]
}}
I'm not sure about how to make the second foreach/for loop to iterate through all the keys.
For iterating JSON, I like to use dynamics. Here's an example:
var result = new Result()
{
Rows = #"{
'BeaconInfoN1ql': [
{
'distance': 2.2705747109792007,
'distanceTesting': 22,
'newDistance': 22,
'receivedDate': '0001-01-01T00:00:00',
'receiverId': '42008780c4b9b329',
'rssi': -73,
'serialNumber': '888'
}
]
}" //other entries omitted for brevity
};
dynamic parsedRows = JsonConvert.DeserializeObject(result.Rows);
foreach (var entry in parsedRows.BeaconInfoN1ql)
Debug.Write(entry.distance);
NOTE: I got rid of the double curly braces from your output in my example.

Categories

Resources