C# Directory path to json formatting - c#

I'm trying to save a folder path in a json file but I can't seem to find/figure out how to get it to parse it correctly
I'm using the following code to write the json file
string location = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string userDataPreset = #"{UserData: [{Language: ""NL"", location: " + location + "}]}";
File.WriteAllText(userData, userDataPreset);
This creates the following json:
{
"UserData": [
{
"Language": "NL",
"location": C:\Users\stage\OneDrive\Documenten
}
]
}
But I need it to become the following, with the double // and "":
{
"UserData": [
{
"Language": "NL",
"location": "C:\\Users\\stage\\OneDrive\\Documenten"
}
]
}
What am I missing to parse this path correctly?

to fix the string you can use an Escape method
location=Regex.Escape(location);
but the most relable method is to create an anonymous object and serialize it
var data = new { UserData = new[] { new { Language = "NL", Location = location } } };
var json = System.Text.Json.JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true});
File.WriteAllText(userData, json);
json
{
"UserData": [
{
"Language": "NL",
"Location": "C:\\Users\\stage\\OneDrive\\Documenten"
}
]
}

Related

How can I search a JSON file in C# by a key value, and then obtain a subsequent key + value?

I have 3 JSON files that all contain the same data structure, however different data.
The structure for all 3 files is as follows:
{
"TokenId": "0",
"rank": "2804"
},
{
"TokenId": "1",
"rank": "977"
},
{
"TokenId": "2",
"rank": "4085"
}
I am trying to create a new JSON file from these 3 files that has the following structure, and yes, they all have the same tokenID values, but slightly different rank values:
{
"TokenId": "0",
"File1Rank": "2804",
"File2Rank": "2802",
"File3Rank": "2809"
},
{
"TokenId": "1",
"File1Rank": "977",
"File2Rank": "983",
"File3Rank": "999"
},
{
"TokenId": "2",
"File1Rank": "4085",
"File2Rank": "4089",
"File3Rank": "4100"
}
How can I search by the tokenId value in each file to obtain the rank value? I can iterate through each valuea in each file to get both values, but I am struggling to create or update the new JSON correctly. The logic I feel I need is if the TokenId is equal to a certain value, then add the rank key/value, but I have not been able to find the answer on how I can do this.
You can use the newtonsoft json library to parse and update the json files.
If your source file structure is:
{
"Tokens": [
{
"TokenId": "0",
"rank": "2804"
},
{
"TokenId": "1",
"rank": "977"
},
{
"TokenId": "2",
"rank": "4085"
}
]
}
Pseudo code:
using Newtonsoft.Json
using Newtonsoft.Json.Linq
void Main()
{
dynamic objFinal = JObject.Parse("{ 'Tokens':[] }");
JArray finalArray = (JArray)objFinal["Tokens"];
DirectoryInfo dir = new DirectoryInfo(#"D:\Projects\JsonFiles\");
foreach(var file in dir.GetFiles("*.json"))
{
dynamic objJson = JObject.Parse(File.ReadAllText(file.FullName));
JArray tokens = (JArray)objJson["Tokens"];
foreach(JToken token in tokens)
{
JToken searchResult = finalArray.Where(t=> Convert.ToString(t["TokenId"])==Convert.ToString(token["TokenId"])).FirstOrDefault();
if(searchResult==null)
{
//push new tokenid
JArray newFileRanks = new JArray();
newFileRanks.Add(token["rank"]);
dynamic newToken = new JObject();
newToken["TokenId"] = token["TokenId"];
newToken["fileRanks"] = newFileRanks;
finalArray.Add(newToken);
}
else
{
//append to fileRanks
JArray existingFileRanks = (JArray)searchResult["fileRanks"];
dynamic fileRankExists = existingFileRanks.Where(t=> Convert.ToString(t)==Convert.ToString(token["rank"])).FirstOrDefault();
if(fileRankExists==null)
{
existingFileRanks.Add(token["rank"]);
}
}
}
}
Console.Write(JsonConvert.SerializeObject(objFinal));
}
Final output:
{
"Tokens": [
{
"TokenId": "0",
"fileRanks": [ "2804", "2801" ]
},
{
"TokenId": "1",
"fileRanks": [ "977", "972" ]
},
{
"TokenId": "2",
"fileRanks": [ "4085", "4083" ]
}
]
}

how to work with nested json object in c#

api return json which is nested and i dont know to retrieve data from it and map it to my model. i want to retrieve the data from nested but not sure how to do this with index and value. Thanks in Advance.
public class MikesExcelModel
{
//public int id;
//public object AuthorizingManagerId;
public string Name;
//public DateTime UpdateDate;
public string Phone;
public string Email;
}
public class MikesExcelResults
{
public List<MikesExcelModel> value = new List<MikesExcelModel>();
}
public List<MikesExcelModel> GetExcel()
{
using (HttpClient client = new HttpClient())
{
addToken(client);
var result = client.GetAsync("https://graph.microsoft.com/beta/sites/ucfdev.sharepoint.com,4c319763-130d-4ee1-bc1f-72543da0a847,8a2f59f4-9d56-4aec-be21-33d0347293d1/drives/b!Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m/items/01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH/workbook/worksheets('sheet1')/tables(%27%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D%27)/rows").Result;
if (result.IsSuccessStatusCode)
{
var responseContent = result.Content;
// by calling .Result you are synchronously reading the result
string responseString = responseContent.ReadAsStringAsync().Result;
JavaScriptSerializer serialiser = new JavaScriptSerializer();
// dynamic apiResult = serialiser.DeserializeObject(responseString);
return Utilities.DeserializeObject<MikesExcelResults>(result.Content.ReadAsStringAsync().Result).value;
}
else
throw new Exception("Couldn't get excel datas.");
}
}
}
Data return by api looks like this:
{
"#odata.context": "https://graph.microsoft.com/beta/$metadata#sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets('sheet1')/tables('%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D')/rows",
"value": [
{
"#odata.id": "/sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets(%27%7B00000000-0001-0000-0000-000000000000%7D%27)/tables(%27%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D%27)/rows/itemAt(index=0)",
"index": 0,
"values": [
[
"Mike Callahan",
"407-266-1431",
"MTC#ucf.edu"
]
]
},
{
"#odata.id": "/sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets(%27%7B00000000-0001-0000-0000-000000000000%7D%27)/tables(%27%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D%27)/rows/itemAt(index=1)",
"index": 1,
"values": [
[
"Michael Callahan",
"407-823-3455",
"mtcallah#ucf.edu"
]
]
},
{
"#odata.id": "/sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets(%27%7B00000000-0001-0000-0000-000000000000%7D%27)/tables(%27%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D%27)/rows/itemAt(index=2)",
"index": 2,
"values": [
[
"cvcfcv",
"zVCCvc",
"cvvvvb"
]
]
}
]
}
Maybe traditional way to extract JSON data with Newtonsoft.Json library.
Convert jsonData to JObject (via JObject.Parse).
Get first-level value.
Get second-level values.
Flatten second-level values.
From
[[["Mike Callahan", "407-266-1431", "MTC#ucf.edu"], ...]]
To
[["Mike Callahan", "407-266-1431", "MTC#ucf.edu"], ...]
Convert flattenChildrenValues to List<MikesExcelModel>.
Add List<MikesExcelModel> to results.value
using System;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
var jsonData = #"{
""#odata.context"": ""https://graph.microsoft.com/beta/$metadata#sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets('sheet1')/tables('%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D')/rows"",
""value"": [
{
""#odata.id"": ""/sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets(%27%7B00000000-0001-0000-0000-000000000000%7D%27)/tables(%27%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D%27)/rows/itemAt(index=0)"",
""index"": 0,
""values"": [
[
""Mike Callahan"",
""407-266-1431"",
""MTC#ucf.edu""
]
]
},
{
""#odata.id"": ""/sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets(%27%7B00000000-0001-0000-0000-000000000000%7D%27)/tables(%27%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D%27)/rows/itemAt(index=1)"",
""index"": 1,
""values"": [
[
""Michael Callahan"",
""407-823-3455"",
""mtcallah#ucf.edu""
]
]
},
{
""#odata.id"": ""/sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets(%27%7B00000000-0001-0000-0000-000000000000%7D%27)/tables(%27%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D%27)/rows/itemAt(index=2)"",
""index"": 2,
""values"": [
[
""cvcfcv"",
""zVCCvc"",
""cvvvvb""
]
]
}
]
}";
var jsonObj = JObject.Parse(jsonData);
// Get first-level value
JArray jsonValue = jsonObj["value"] as JArray;
// Get second-level values
var childrenValues = jsonValue.Children<JObject>()["values"];
// Flatten second-level values
var flattenChildrenValues = childrenValues.Values<JArray>() as IEnumerable<JArray>;
// Read flattenChildrenValues to List<MikesExcelModel>
List<MikesExcelModel> excelModels = flattenChildrenValues
.Select(x => new MikesExcelModel
{
Name = x[0].ToString(),
Phone = x[1].ToString(),
Email = x[2].ToString()
})
.ToList();
// Add List<MikesExcelModel> to results.value
MikesExcelResults results = new MikesExcelResults();
results.value.AddRange(excelModels);
foreach (var model in results.value)
{
Console.WriteLine(String.Format("Name: {0}, Phone: {1}, Email: {2}", model.Name, model.Phone, model.Email));
}
Sample program

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 generate JSON file from JSON Schema with addition of data in C#

I am currently working on an application that will convert the SQL Query Result to JSON. However the converted JSON must fit into a part of JSON Schema. I had done the first part and also load the Schema into the application, however I have no idea how to generate a JSON file based on the Schema I loaded and also filled in the data that I get from the SQL Query Result.
Here is the part of the sample of schema:
"security": [
{
"Default": []
}
],
"components": {
"schemas": {
"Event": {
"title": "Event",
"required": [
"object",
"body"
],
"type": "object",
"properties": {
"object": {
"type": "string",
"description": "The object name involved in the event",
"enum": [
"business_partners"
]
},
"body": {
"type": "object",
"description": "The core data of the event",
"required": [
"name1",
"country",
],
"properties": {
"name1": {
"type": "string",
"description": "Partner Name 1"
},
"name2": {
"type": "string",
"description": "Partner Name 2"
},
"country": {
"type": "string",
"description": "Country ISO Code"
},
}
}
}
},
From the query result, I can have the property name1, name2 and country.
After converted to JSON, the query result JSON looks like this:
[
{
"Partner Name 1": "Jenny",
"Partner Name 2": null,
"Country ISO Code": "US",
},
{
"Partner Name 1": "John",
"Partner Name 2": "Alan",
"Country ISO Code": null,
},
]
How can I generate the JSON file with all the other fields in the schema but only filled the value from SQL Query Result into the JSON file?
I'm using Newtonsoft.Json and Newtonsoft.Json.Schema in this project.
NOTE: Other than the data returned by SQL Query Result, my JSON file generated also need those fields that does not exist in the query result.
Here is my code so far:
private IEnumerable<dynamic> ReaderToAnonymmous()
{
//Connect to SQL Database using App.config
string connectionString = ConfigurationManager.AppSettings["SQLConnection"].ToString();
SqlConnection connection = new SqlConnection(connectionString);
//Using Stored Procedure to execute query (Full Script Written inside SQLScript folder)
SqlCommand command = new SqlCommand("Select_Result_Convert_JSON", connection)
{
CommandType = CommandType.StoredProcedure
};
connection.Open();
using (var reader = command.ExecuteReader())
{
var schemaTable = reader.GetSchemaTable();
List<string> colnames = new List<string>();
foreach (DataRow row in schemaTable.Rows)
{
colnames.Add(row["ColumnName"].ToString());
}
while (reader.Read())
{
var data = new ExpandoObject() as IDictionary<string, Object>;
foreach (string colname in colnames)
{
var val = reader[colname];
data.Add(colname, Convert.IsDBNull(val) ? null : val);
}
yield return (ExpandoObject)data;
}
}
}
private void LoadSchema()
{
using (StreamReader file = File.OpenText("..\\..\\sampleschema.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
schema = JSchema.Load(reader);
}
}
public void generateJSONFile(string fileName)
{
try
{
var ObjectData = ReaderToAnonymmous(); //Get the SQL Query Result and Convert it to object
LoadSchema();
var Json = JsonConvert.SerializeObject(ObjectData);
JArray BP = new JArray(Json);
if (BP.IsValid(schema))
{
BP.Merge(schema);
if (!String.IsNullOrEmpty(fileName)) //If user enter any file name
{
string basePath = String.Format("{0}{1}{2}", "C:\\", fileName, ".json");
using (StreamWriter file = File.CreateText(basePath)) //Create JSON File based on input name
{
JsonSerializer serializer = new JsonSerializer();
serializer.Formatting = Formatting.Indented; //Format the JSON
serializer.Serialize(file, BP);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Message", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
Please please help! Thank you!

Json Searching Data Structures

This is my Data Structure and I'm trying to access it with simpleJason, through unity/c#, I have accidentally gotten the right data here and there, and otherwise gotten completely empty arrays, I'd like to know if my JSON file is improperly setup for my data structure, or if the parser is somehow falling though, or not properly matching what I'm looking for.
JSON File:
{
"categories": [
{
"name" : "entertainment",
"projects": [
{
"name": "Awards",
"description": "Awards Shows",
"credits": [
"Lead Engineer - Dave Jones",
"VFX Supervisor - John Adrian",
"CG Supervisor - Evan Klein"
],
"meta": [
"awards",
"show",
"stars",
"red carpet"
],
"assets": [
{
"name": "Screen Actors Guild Awards",
"filename": "SAG_Awards.mp4",
"icon": "sag.png",
"stereo": false,
"meta": [
"Screen",
"Actors",
"Guild"
]
},
{
"name": "No Awards",
"filename": "No_SAG_Awards.mp4",
"icon": "no_sag.png",
"stereo": false,
"meta": [
"Screen",
"Actors",
"Guild"
]
},
{
"name": "None Awds",
"filename": "None_SAG_Awards.mp4",
"icon": "none_sag.png",
"stereo": false,
"meta": [
"Screen",
"Actors",
"Guild"
]
}
]
}
]
}
]
}
This is the struct :
private struct jsonAsset {
public string category;
public string project;
public string description;
public string[] credits;
public string[] meta;
public string asset;
public FileInfo file;
public FileInfo icon;
public bool stereo;
public bool overUnder;
};
This is the function:
jsonAsset LoadSceneDataFromJSON(FileInfo jsonFile)
{
jsonAsset asset = new jsonAsset();
Debug.Log("Processing : " + jsonFile);
// Parse File for Data
var N = JSON.Parse(File.ReadAllText(jsonFile.FullName));
var cat_arr = N["categories"].AsArray;
asset.category = N["categories"]["name"].Value;
Debug.Log(N["categories"]["projects"]["assets"]["filename"].Value);
foreach (JSONNode n in cat_arr)
{
asset.project = n["name"].Value;
// Credits
var proj_credits = n["credits"].AsArray;
foreach (JSONNode pc in proj_credits)
{
asset.credits[asset.credits.Length] = pc["credits"].Value;
}
// Project Meta
var proj_meta = n["meta"].AsArray;
foreach (JSONNode pm in proj_meta)
{
asset.meta[asset.meta.Length] = pm["meta"].Value;
}
// Project Array
var proj_arr = n["projects"].AsArray;
foreach (JSONNode nn in proj_arr)
{
var asset_arr = nn["assets"].AsArray;
asset.asset = nn["assets"]["name"].Value;
foreach (JSONNode nnn in asset_arr)
{
asset.asset = nnn["name"].Value;
asset.file = new FileInfo(m_dir + nnn["filename"].Value);
asset.icon = new FileInfo(m_dir + nnn["icon"].Value);
var asset_meta = nnn["meta"].AsArray;
foreach (JSONNode am in asset_meta)
{
asset.meta[asset.meta.Length] = am.Value;
}
}
}
}
return asset;
}
You are treating projects as an object instead of an array.
I dont know what JSON library you are using to give you guidance, but something like this will probably work:
N["categories"]["projects"][0]["assets"]["filename"].Value

Categories