I have the following JSON string:
[
{
"Id": 1,
"UserName": "Test1",
"UserPassword": "Test1",
"FirstName": "TF1",
"LastName": "TL1",
"Mobile": "Test1",
"Email": "TE1",
"CreatedDate": "2022-05-29T00:00:00.000Z"
},
{
"Id": 4,
"UserName": "Test4",
"UserPassword": "Test4",
"FirstName": "T4F",
"LastName": "TL4",
"Mobile": "Test4",
"Email": "TE4",
"CreatedDate": "2022-05-29T00:00:00.000Z"
},
{
"Id": 3,
"UserName": "Test3",
"UserPassword": "Test3",
"FirstName": "TF3",
"LastName": "TL3",
"Mobile": "Test3",
"Email": "TE3",
"CreatedDate": "2022-05-29T00:00:00.000Z"
},
{
"Id": 7,
"UserName": "Test7",
"UserPassword": "Test7",
"FirstName": "T7F",
"LastName": "TL7",
"Mobile": "Test7",
"Email": "TE7",
"CreatedDate": "2022-05-29T00:00:00.000Z"
},
{
"Id": 7,
"UserName": "Test7",
"UserPassword": "Test7",
"FirstName": "T7F",
"LastName": "TL7",
"Mobile": "Test7",
"Email": "TE7",
"CreatedDate": "2022-05-29T00:00:00.000Z"
},
{
"Id": null,
"UserName": "PT",
"UserPassword": "PT",
"FirstName": null,
"LastName": null,
"Mobile": null,
"Email": null,
"CreatedDate": null
},
{
"Id": null,
"UserName": "CTest",
"UserPassword": "CTest",
"FirstName": null,
"LastName": null,
"Mobile": null,
"Email": null,
"CreatedDate": null
},
{
"Id": 5,
"UserName": "Test5",
"UserPassword": "Test5",
"FirstName": "TF5",
"LastName": "TL5",
"Mobile": "Test5",
"Email": "TE5",
"CreatedDate": "2022-05-29T00:00:00.000Z"
}
]
And would like to read the all the values of the UserName & UserPassword fields of the string into the following lists:
var UserName = new List<string>();
var UserPassword = new List<string>();
Create a class containing at least those two properties (it could have the others also):
class User
{
public string UserName;
public string UserPassword;
}
Parse the JSON using a suitable parser, such as Json.NET
var list = JsonConvert.DeserializeObject<List<User>>(yourJson);
Use Linq to pull out the data you want
var UserName = list.Select(u => u.UserName).ToList();
var UserPassword = list.Select(u => u.UserPassword ).ToList();
dotnetfiddle
From your JSON string
string JSON_String = ...;
You can also extract the data you want with the help of Regex and LINQ. Here is an example
var UserName = Regex
.Matches(JSON_String, "\"UserName\":\\s*\"\\w+\"")
.Cast<Match>()
.Select(m => m.Value)
.Select(s => Regex.Match(s, "\"\\w+\"", RegexOptions.RightToLeft).Value)
.Select(s => s.Substring(1, s.Length - 2))
.ToList();
var UserPassword = Regex
.Matches(JSON_String, "\"UserPassword\":\\s*\"\\w+\"")
.Cast<Match>()
.Select(m => m.Value)
.Select(s => Regex.Match(s, "\"\\w+\"", RegexOptions.RightToLeft).Value)
.Select(s => s.Substring(1, s.Length - 2))
.ToList();
Related
I made a feature where user can sign in Apple in Android using Unity Firebase. The code is:
var providerData = new FederatedOAuthProviderData
{
ProviderId = "apple.com"
};
var provider = new FederatedOAuthProvider();
provider.SetProviderData(providerData);
await auth.SignInWithProviderAsync(provider).ContinueWith(task =>
{
var result = task.Result;
});
my question is: how to retrieve apple id token from task.Result ?
edit: the data return contains 2 parts:
user info
{
"PhotoUrl": null,
"DisplayName": "",
"Email": "bangminhkiet#hoppergames.io",
"IsAnonymous": false,
"IsEmailVerified": true,
"Metadata": {
"LastSignInTimestamp": 1660117698962,
"CreationTimestamp": 1660116775373
},
"PhoneNumber": "",
"ProviderData": [
{
"PhotoUrl": null,
"UserId": "elba7GqsGccUvQiYnEZr5KTtHlv2",
"Email": "bangminhkiet#hoppergames.io",
"DisplayName": "",
"ProviderId": "firebase"
},
{
"PhotoUrl": null,
"UserId": "000435.d5a5ca436f7645f992af1e1cc4d8e97b.0728",
"Email": "bangminhkiet#hoppergames.io",
"DisplayName": "",
"ProviderId": "apple.com"
}
],
"ProviderId": "firebase",
"UserId": "elba7GqsGccUvQiYnEZr5KTtHlv2"
}
extra info
{
"Profile": {
"at_hash": "W89x3Dkr7ri-mMHu2bHdiw",
"aud": "com.m.obirix.mbgk.web",
"auth_time": 1660117696,
"email": "bangminhkiet#hoppergames.io",
"email_verified": "true",
"exp": 1660204098,
"iat": 1660117698,
"iss": "https://appleid.apple.com",
"nonce_supported": true,
"sub": "000435.d5a5ca436f7645f992af1e1cc4d8e97b.0728"
},
"ProviderId": "apple.com",
"UserName": "",
"UpdatedCredential": {
"Provider": ""
}
}
I am trying to filter nested data but the catch is, the children I am also trying to filter are of a different type.
I have data that looks like this:
{
"value": [
{
"UserName": "scottketchum",
"FirstName": "Scott",
"LastName": "Ketchum",
"MiddleName": null,
"Gender": "Male",
"Age": null,
"Emails": [
"Scott#example.com"
],
"FavoriteFeature": "Feature1",
"Features": [],
"AddressInfo": [
{
"Address": "2817 Milton Dr.",
"City": {
"Name": "Albuquerque",
"CountryRegion": "United States",
"Region": "NM"
}
}
],
"HomeAddress": null
},
{
"UserName": "harryingram",
"FirstName": "Harry",
"LastName": "Ingram",
"MiddleName": null,
"Gender": "Male",
"Age": null,
"Emails": [
"Harry#example.com"
],
"FavoriteFeature": "Feature2",
"Features": [],
"AddressInfo": [
{
"Address": "123 Scott Ln.",
"City": {
"Name": "Nashville",
"CountryRegion": "United States",
"Region": "TN"
}
}
],
"HomeAddress": null
}
]
}
I need to be able to type the word "Scott" in my search field and return any person that has the name "Scott" or has an Address with the word "Scott" in it. So, ideally, the search would return both people.
void searchitemfromjson(string s)
{
var text = File.ReadAllText("D://jsontest.txt");
var jObject1 = JObject.Parse(text)["value"];
var searchs = new List<string>();
foreach (var item in jObject1)
{
var jObjitem = JObject.Parse(item.ToString());
IList<string> keys = jObjitem.Properties().Select(p => p.Name).ToList();
foreach (var k in keys)
{
if (k == "UserName")
{
if (jObjitem[k].ToString().Contains(s)) searchs.Add(jObjitem[k].ToString());
}
else if(k == "AddressInfo")
{
if(jObjitem["AddressInfo"][0]["Address"].ToString().Contains(s)) searchs.Add(jObjitem[k].ToString()); ;
}
}
}
}
{
"STATUS": "OK",
"projects": [
{
"startDate": "",
"last-changed-on": "2019-01-03T11:46:14Z",
"logo": "",
"created-on": "2018-12-12T10:04:47Z",
"privacyEnabled": false,
"status": "active",
"boardData": {},
"replyByEmailEnabled": true,
"harvest-timers-enabled": false,
"description": "",
"category": {
"color": "",
"id": "",
"name": ""
},
"id": "322852",
"overview-start-page": "default",
"start-page": "projectoverview",
"integrations": {
"xero": {
"basecurrency": "",
"countrycode": "",
"enabled": false,
"connected": "NO",
"organisation": ""
},
"sharepoint": {
"account": "",
"foldername": "root",
"enabled": false,
"folder": "root"
},
"microsoftConnectors": {
"enabled": false
},
"onedrivebusiness": {
"account": "",
"foldername": "root",
"enabled": false,
"folder": "root"
}
},
"defaults": {
"privacy": ""
},
"notifyeveryone": false,
"filesAutoNewVersion": false,
"defaultPrivacy": "open",
"tasks-start-page": "default",
"starred": false,
"announcementHTML": "",
"isProjectAdmin": true,
"name": "Project 2",
"company": {
"is-owner": "1",
"id": "78494",
"name": "MCG Company"
},
"endDate": "",
"announcement": "",
"show-announcement": false,
"subStatus": "current",
"tags": []
},
{
"startDate": "",
"last-changed-on": "2018-12-11T17:52:57Z",
"logo": "",
"created-on": "2018-11-26T11:11:00Z",
"privacyEnabled": false,
"status": "active",
"boardData": {},
"replyByEmailEnabled": true,
"harvest-timers-enabled": false,
"description": "",
"category": {
"color": "",
"id": "",
"name": ""
},
"id": "321041",
"overview-start-page": "default",
"portfolioBoards": [
{
"card": {
"id": "4771"
},
"board": {
"id": "544",
"name": "Project Implementations",
"color": "#F39C12"
},
"column": {
"id": "1573",
"name": "Go Live",
"color": "#F1C40F"
}
}
],
"start-page": "projectoverview",
"integrations": {
"xero": {
"basecurrency": "",
"countrycode": "",
"enabled": false,
"connected": "NO",
"organisation": ""
},
"sharepoint": {
"account": "",
"foldername": "root",
"enabled": false,
"folder": "root"
},
"microsoftConnectors": {
"enabled": false
},
"onedrivebusiness": {
"account": "",
"foldername": "root",
"enabled": false,
"folder": "root"
}
},
"defaults": {
"privacy": ""
},
"notifyeveryone": false,
"filesAutoNewVersion": false,
"defaultPrivacy": "open",
"tasks-start-page": "default",
"starred": false,
"announcementHTML": "",
"isProjectAdmin": true,
"name": "Project One",
"company": {
"is-owner": "1",
"id": "78494",
"name": "MCG Company"
},
"endDate": "",
"announcement": "",
"show-announcement": false,
"subStatus": "current",
"tags": []
}
]
}
This is the JSON response that I'm getting from an app, and there are a lot of other API gets that are returning the same kind of response (nested), so this has to be done dynamically as the user is adding API calls from a config file, so I cannot make pre-made classes with gets and sets.
My goal is to transform this data into a datatable to be inserted into a database
When I see a nested column, my goal is to have the parent column name attached to it with an "_" ex: category_id = ""
or integrations_xero_basecurrency = "", etc..
This is the code that I used to tabulate the data, but in the code it's only taking the column if it's a JValue (key and value), and I'm not able for the life of me to create a proper loop that will do the trick.
public DataTable Tabulate(string jsonContent)
{
var jsonLinq = JObject.Parse(jsonContent);
// Find the first array using Linq
var srcArray = jsonLinq.Descendants().Where(d => d is JArray).First();
//Console.WriteLine("extarcted data:" + srcArray);
var trgArray = new JArray();
foreach (JObject row in srcArray.Children<JObject>())
{
var cleanRow = new JObject();
foreach (JProperty column in row.Properties())
{
// Only include JValue types
if (column.Value is JValue)
{
cleanRow.Add(column.Name, column.Value);
}
}
trgArray.Add(cleanRow);
}
DataTable dt = JsonConvert.DeserializeObject<DataTable>(trgArray.ToString());
return dt;
}
How about something like this:
public DataTable Tabulate(string jsonContent)
{
var jsonLinq = JObject.Parse(jsonContent);
// Find the first array using Linq
var arrayProp = jsonLinq.Properties().First(p => p.Value is JArray);
var srcArray = (JArray)arrayProp.Value;
// Set up a regex consisting of the array property name and subscript
// (e.g. "projects[0]."), which we will strip off
var regex = new Regex($#"^{arrayProp.Name}\[\d+\]\.");
// Flatten each object of the original array
// into new objects and put them in a new array
var trgArray = new JArray(
srcArray.Children<JObject>()
.Select(row => new JObject(
row.Descendants()
.OfType<JProperty>()
.Where(p => p.Value is JValue)
.Select(p => new JProperty(
regex.Replace(p.Value.Path, "").Replace(".", "_"),
p.Value
))
))
);
// Convert the new array to a DataTable
DataTable dt = trgArray.ToObject<DataTable>();
return dt;
}
Working demo: https://dotnetfiddle.net/yrmcSQ
I am facing an issue while writing query to make a group by on inner list data to filter the outer list.
I have a collection structure like
"products"
{
"id": "97",
"name": "YI1",
"projects": [
{
"id": "92",
"name": "MUM",
"branches": [
{
"id": "62",
"name": "ON Service",
"geographyid": "84",
"geographyname": "North America",
"countryid": "52",
"countryname": "Canada"
}
],
"customers": [
{
"id": "80",
"name": "HEALTH SCIENCES"
}
]
}
],
},
"products"
{
"id": "96",
"name": "YI2",
"projects": [
{
"id": "94",
"name": "HHS",
"branches": [
{
"id": "64",
"name": "Hamilton ON Service",
"geographyid": "44",
"geographyname": "Asia",
"countryid": "58",
"countryname": "China"
}
],
"customers": [
{
"id": "40",
"name": "SCIENCES"
}
]
}
],
]
}
I am trying to have a new collection which can return an output as below
"Geography"{
"geographyid": "44",
"geographyname": "Asia",
"Country"
{
"countryid": "58",
"countryname": "China",
"branches"
{
"id": "94",
"name": "HHS
"customers"
{
"id": "40",
"name": "SCIENCES"
"projects"
{
"id": "94",
"name": "HHS",
"products"
{
"id": "96",
"name": "YI2",
}
}
},
}
}
},
"Geography"{
"geographyid": "84",
"geographyname": "North America"
"Country"
{
"countryid": "52",
"countryname": "Canada"
"branches"
{
"id": "62",
"name": "ON Service",
"customers"
{
"id": "80",
"name": "HEALTH SCIENCES"
"projects"
{
"id": "92",
"name": "MUM",
"products"
{
"id": "97",
"name": "YI1",
}
}
},
}
}
}
I tried multiple options and also write below query but I am still not getting required result.
var treeGroup = siteList.SelectMany(a => a.projects.Select(b => new { A = a, B = b }).ToList()).ToList()
.GroupBy(ol => new { ol.B.geographyid, ol.B.geographyname })
.Select(gGroup => new TreeNodes
{
id = gGroup.Key.geographyid,
name = gGroup.Key.geographyname,
type = Costants.geographyTreeNode,
parentid = string.Empty,
children = gGroup
.GroupBy(ol => new { ol.B.countryid, ol.B.countryname })
.Select(cGroup => new TreeNodes
{
id = cGroup.Key.countryid,
name = cGroup.Key.countryname,
type = Costants.countryTreeNode,
parentid = gGroup.Key.geographyid,
children = cGroup
.GroupBy(ol => new { ol.B.id, ol.B.name })
.Select(sGroup => new TreeNodes
{
id = sGroup.Key.id,
name = sGroup.Key.name,
type = Costants.branchTreeNode,
parentid = cGroup.Key.countryid,
children = sGroup
.Select(ol => new TreeNodes { id = ol.A.id, name = ol.A.name, type = Costants.siteTreeNode, parentid = sGroup.Key.id, children = new List<TreeNodes>() })
.ToList()
})
.ToList()
})
.ToList()
})
.ToList();
I can use looping logic to get the result, but I want to avoid it and try something with linq or lmbda expression.
I am able to resolve the issue. I took an additional parameters for Customers and then used the same with selectmany function on branches
I have some problems with jobject and jarray linq query. I get this error:
Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'.
My code:
string fetchResult = JsonConvert.SerializeObject(sidebar, Formatting.Indented);
JObject rss = JObject.Parse(fetchResult);
var jsonModel = from item in (JArray)rss["RegistrationCase"]
select new DataList
{
RegistrationTypeName = item["RegistrationTypeName"].Value<string>(), };
If i remove (Jarray) i get: Cannot access child value on Newtonsoft.Json.Linq.JProperty.
Json, jobject: e.g: i want RegistrationTypeName, FirstName and the value of JournalNumber.
{
"Status": null,
"RegistrationCase": {
"RegistrationTypeName": " ",
"ExpireDate": null,
"PersonId": 7,
"Person": {
"FirstName": " ",
"GenderValue": 2,
"Gender": 2,
},
"UserId": 7,
"User": {
"UserName": "NO-DOM\\wme",
"LastName": null,
"Id": 7,
},
"Transactions": [],
"Comments": [],
"CustomData": [
{
"Key": "JournalNumber",
"Value": "0654-84148-00000-25",
"Id": 3,
},
{
"Key": "IsConsentGiven",
"Value": "False",
"Id": 4,
},
{
],
"FileId": null,
"File": null,
"Id": 7,
}
}
u can get these values directly like :
var RegistrationTypeName = rss["RegistrationCase"]["RegistrationTypeName"];
var FirstName = rss["RegistrationCase"]["Person"]["FirstName"];
var JournalNumber = rss["RegistrationCase"]["CustomData"][0]["Value"];