Delete JSON Data inside Property based on ID in C# - 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);

Related

Unable to Write json variable c# getting an error

I get an error when I try to serialize or update a json file. I just want to update the value of "balance" inside a json file and I got the idea here... I can't seem to make it work for my project. The Users.json file does not change whenever I check it.
here is my code:
Users.json
[
{
"id": 1,
"username": "sachin",
"password": "sachin1",
"firstName": "Sachin",
"lastName": "Karnik",
"birthdate": "2011-6-14",
"balance": 20000,
"cardNumber": 12345
},
{
"id": 2,
"username": "dina",
"password": "dina1",
"firstName": "Dina",
"lastName": "Meyers",
"birthdate": "2012-8-20",
"balance": 20000,
"cardNumber": 23456
},
{
"id": 3,
"username": "andy",
"password": "andy1",
"firstName": "Andy",
"lastName": "Rose",
"birthdate": "2010-2-11",
"balance": 20000,
"cardNumber": 34567
}
]
Menu.cs
public static void BankMenu(object? balance, object? user)
{
User[]? Users = JsonConvert.DeserializeObject<User[]>(Login.jsonResponse);
int bal = Convert.ToInt32(balance);
int money;
try{
money = ValidateAmountInput(bal, user);
if (money <= bal && money != 0)
{
bal -= money;
foreach (var usr in Users!)
{
if (usr.FirstName == user?.ToString())
{
usr.Balance = bal;
}
}
var json = JsonConvert.SerializeObject(Users, Formatting.Indented);
File.WriteAllText(Login.jsonResponse, json);
}
}
catch(System.Exception e)
{
WriteLine(e);
}
My Error
you have a bug
File.WriteAllText(Login.jsonResponse, json);
instead of ogin.jsonResponse you have to use a file path
File.WriteAllText(<full file path\Users.json>, json);

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

Recover objects from response.Content.ReadAsStringAsync()

I have a list of Json objectS that I send by API as a result :
{
"Pr": {
"ClientProfil": {
"IdClient": 67,
"FirmName": null,
"NumMember": "OPTOO111",
"FirstName": "EL MONAGI",
"LastName": "ABDELJALIL",
"Email": "jalil_monagi#yahoofr",
"Adress": "7795 10eme avenue",
"City": "Montréal",
"Province": "QC",
"Country": "CA",
"Postalcode": "H2A3B3",
"Tel": "438 995 6475",
"PreferredLanguage": "fr"
},
"Programm": {
"IdProgramm": 9,
"Designation": "OPTO",
"CreationDate": "2020-01-01T00:00:00",
"SuppressionDate": null,
"RenewDate": "2021-01-04T00:00:00",
"StartDate": null,
"IsRenewDate": true
}
}
and in the front office I use the code below
public async Task<ActionResult> Authentificate(FormCollection form)
{
HttpClient client = autentificate();
string userCodePwd = form["fCode"].ToString() + ":" + form["lPwd"].ToString();
userCodePwd = Convert.ToBase64String(Encoding.Default.GetBytes(userCodePwd));
//var decodedAuthenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(userCodePwd));
HttpResponseMessage response = client.GetAsync("api/Login/FindPolice?userCodePasswordArray=" + userCodePwd).Result;
try
{
if (response.IsSuccessStatusCode)
{
string Result = await response.Content.ReadAsStringAsync();
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
dynamic dobj = jsonSerializer.Deserialize<dynamic>(Result);
int StatusCode = (int)response.StatusCode;
if (StatusCode==200) // Existe une assurance pour le client
{
int StatusRequest = dobj["StatusRequest"];
if (StatusRequest==1001)
{
int IdProgram = dobj["IdProgram"];
RootAQII.Profil= JsonConvert.DeserializeObject<Profil>(dobj["Pr"].ToString());
RootAQII.Programm= JsonConvert.DeserializeObject<List<Programm>>(dobj["Programm"].ToString());
if (IdProgram==9)
{
return RedirectToAction("Index", "OPTO");
}
}
}
}
else
{
}
}
catch (Exception e)
{
String message = e.Message;
}
return View();
}
the problem is when I try to parse the result of response for RootOPTOASSURED.Profil
I get this message error :
unexpected character encountered while parsing value: s. path '', line
0, position 0.
there is anyone who has any idea And thanks you in advance :)
Assuming that Result is the json string from above, the line
int IdProgram = dobj["IdProgram"];
Should fail as the only element of dobj should be dobj["PR"]
Besides that you are trying to deserialize a list of Programm entries from a single JSON entry. If Programm is supposed to be a list, than is should appear in []
{
"Pr": {
"ClientProfil": {
"IdClient": 67,
"FirmName": null,
"NumMember": "OPTOO111",
"FirstName": "EL MONAGI",
"LastName": "ABDELJALIL",
"Email": "jalil_monagi#yahoofr",
"Adress": "7795 10eme avenue",
"City": "Montréal",
"Province": "QC",
"Country": "CA",
"Postalcode": "H2A3B3",
"Tel": "438 995 6475",
"PreferredLanguage": "fr"
},
"Programm":
[
{
"IdProgramm": 9,
"Designation": "OPTO",
"CreationDate": "2020-01-01T00:00:00",
"SuppressionDate": null,
"RenewDate": "2021-01-04T00:00:00",
"StartDate": null,
"IsRenewDate": true
}
]
}
}
Either that or change the line
RootAQII.Programm= JsonConvert.DeserializeObject<List<Programm>>(dobj["Programm"].ToString());
to
RootAQII.Programm= JsonConvert.DeserializeObject<Programm>(dobj["Programm"].ToString());
I have put an example at rextester

JSON - LINQ Query for object or an array to group two data with same key value pair

Consider I have a JSON data as:
{
"entities":[
{
"republish": false,
"OrgID": "",
"createdby": "730",
"questions": [
{
"sequence": "5",
"QuestionId": "57BB6DDC-A90A-10EE-E224-EC658A825871",
"metadata": [
{
"key": "Group",
"value": 0
},
{
"key": "Part",
"value": "0"
}
]
},
{
"sequence": "4",
"QuestionId": "57BB6DDC-A90A-10EE-E224-EC658A825871",
"metadata": [
{
"key": "Group",
"value": 1
},
{
"key": "Part",
"value": "A"
}
]
},
{
"sequence": "3",
"QuestionId": "57BB6DDC-A90A-10EE-E224-EC658A825871",
"metadata": [
{
"key": "Group",
"value": 1
},
{
"key": "Part",
"value": "B"
}
]
}
]
}
]
}
As you can see I have a list of questions available and in each question, I have a metadata which holds Key-Value pair.
Above example demonstrates, I have 3 questions and out of it 2 question, metadata key-value is "Group 1".
Now I want to do is combine the questions with a same key-value pair and treat it as one.
so in my final case, I will have 2 questions instead of 3. And out of that one question will have two separate questions inside.
And I want to achieve this using Linq query. And if possible please use Newtonsoft for parse if needed. I have been stuck for long onto this.
Things I have done:
public virtual HttpResponseMessage AddQuestionsToStandardMaster(TaxonomyMetaData objQuestion)
{
List<ResponseEntity> objResponseList = new List<ResponseEntity>();
try
{
if (ModelState.IsValid)
{
foreach (var objEntity in objQuestion.Entities)
{
EntityResponse objentityresponse = new EntityResponse();
ResponseEntity objResponse = new ResponseEntity();
}
List<Question> objQuestionList = new List<Question>();
if (objEntity.Questions.Length > 0)
{
foreach (var item in objEntity.Questions)
{
int questionTypeid = 0;
dynamic objQuestionJson = JObject.Parse(item.ToString())
}
}
}
Question objCurrentQuestion = new Question();
Question objQuestionforDelete = new Question();
JObject itemToParese = new JObject();
string SingleQuestionJson = objQuestionJson.GetValue("QuestionData").ToString();
string questionstem = "";
Regex rgx = new Regex("/\'");
objCurrentQuestion.Sequence = Convert.ToInt32(objQuestionJson.GetValue("sequence"));
objCurrentQuestion.tag = objQuestionJson.tag.ToObject<JToken[]>(); ;
objCurrentQuestion.metadata = objQuestionJson.metadata.ToObject<JToken[]>();
objCurrentQuestion.SingleQuestionJson = rgx.Replace(SingleQuestionJson, "'");
objCurrentQuestion.QuestionsType = questionTypeid;
objCurrentQuestion.QuestionsId = new Guid(objQuestionJson.GetValue("QuestionId").ToString());
objCurrentQuestion.VersionNo = Convert.ToInt32(objQuestionJson.GetValue("VersionNo"));
objCurrentQuestion.DisplayQuestionId = Convert.ToString(objQuestionJson.GetValue("DisplayQuestionId"));
objCurrentQuestion.OriginalQuestionId = Convert.ToString(objQuestionJson.GetValue("OriginalQuestionId"));
objCurrentQuestion.PassageText = Convert.ToString(objQuestionJson.GetValue("passage_text"));
objCurrentQuestion.PassageCode = Convert.ToString(objQuestionJson.GetValue("passage_id"));
objCurrentQuestion.PassageTitle = Convert.ToString(objQuestionJson.GetValue("passage_title"));
objCurrentQuestion.IsPublished = Convert.ToByte(true);
objCurrentQuestion.ProductId = objEntity.ProductID;
foreach (var metadata in objCurrentQuestion.metadata)
{
switch (metadata["key"].ToString())
{
case "Group":
objCurrentQuestion.Group = Convert.ToInt32(metadata["value"].ToString());
break;
case "Part":
objCurrentQuestion.Part = metadata["value"].ToString();
break;
}
}
objQuestionList.Add(objCurrentQuestion);
int counter = 1;
//Here I get the data in a group which needs to coverted to JSOn and then replace the original JSON data with this. But I know this is irrelevant to what we need to achieve.
var yui = objQuestionList.Where(tma => tma.Group == counter).Select(t => t).GroupBy(s => new { s.Group }).Where(p => p.Count() > 1).ToList();
//After proper conversion I need to enter this data to a database.
I am a bit unclear on what do you mean by make it
combine the questions with a same key-value pair and treat it as one
But here is how you can group by the JSON into groups in metadata you can do a custom select to what ever you want.
var text = #"{
""entities"":[
{
""republish"": false,
""OrgID"": """",
""createdby"": ""730"",
""questions"": [
{
""sequence"": ""5"",
""QuestionId"": ""57BB6DDC-A90A-10EE-E224-EC658A825871"",
""metadata"": [
{
""key"": ""Group"",
""value"": 0
},
{
""key"": ""Part"",
""value"": ""0""
}
]
},
{
""sequence"": ""4"",
""QuestionId"": ""57BB6DDC-A90A-10EE-E224-EC658A825871"",
""metadata"": [
{
""key"": ""Group"",
""value"": 1
},
{
""key"": ""Part"",
""value"": ""A""
}
]
},
{
""sequence"": ""3"",
""QuestionId"": ""57BB6DDC-A90A-10EE-E224-EC658A825871"",
""metadata"": [
{
""key"": ""Group"",
""value"": 1
},
{
""key"": ""Part"",
""value"": ""B""
}
]
}
]
}
]
}";
var json = JObject.Parse(text);
var groupedData = from entity in json["entities"]
from question in entity["questions"]
group question by question["metadata"][0]["value"] into questionGroup
select questionGroup;
foreach (var data in groupedData)
{
Console.WriteLine("_____________________");
Console.WriteLine("Group");
Console.WriteLine(data.Key);
foreach (var question in data)
{
Console.WriteLine(question["QuestionId"]);
}
Console.WriteLine("_____________________");
}
If "Group" is not always the fist item in the array you can do
question["metadata"].First(md => md.Value<string>("key") == "Group")["value"]
to get it.

Newtonsoft JSON - create JArray in JArray

I am trying to create JSON array using Newtonsoft JSON API but its giving me error. I want to achieve structure like
[
{
"id":"26",
"appsurvey":"1",
"fk_curriculumid":"70",
"status":"Completed",
"lastaccessedon":"2014-06-20 09:18:54",
"questions":[
{
"feedback":"6",
"questionid":"1"
},
{
"feedback":"8",
"questionid":"2"
},
{
"feedback":"1",
"questionid":"3"
}
],
"fk_clientid":"24",
"learnerid":"260"
}
]
I want ot add questions array for multiple time but it is giving me error
Can not add property questions to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.
Here is my code:
JArray surveytrackingA = new JArray();
/*code to add
[
{"id":"26",
"appsurvey":"1",
"fk_curriculumid":"70",
"status":"Completed",
"lastaccessedon":"2014-06-20 09:18:54"}]
*/
for (int i = 0; i < surveytrackingA.Count; i++)
{
JObject surveytrackD = (JObject)surveytrackingA[i];
string queryOne = "select * from table101 where fk_curriculumid='"
+ surveytrackD["fk_curriculumid"].ToString()
+ "' and fk_surveyid='"
+ surveytrackD["appsurvey"].ToString() + "'";
JArray questionsA = new JArray();
using (var stmt = await App.localDB.PrepareStatementAsync(queryOne))
{
while (await stmt.StepAsync())
{
JObject questionD = new JObject();
questionD.Add("questionid", stmt.GetTextAt(5));
questionD.Add("feedback", stmt.GetTextAt(6));
questionsA.Add(questionD);
}
}
surveytrackD.Add("questions", questionsA); /*error occurred here when second question array is getting inserted in surveyTrackD*/
surveytrackingA.Add(surveytrackD);
}
Can anyone please correct me. Thanks in advance.
Update:
surveytrackD have the json data,
{
"fk_clientid": "24",
"learnerid": "260",
"appsurvey": "1",
"id": "26",
"fk_curriculumid": "70",
"status": "completed",
"lastaccessedon": "2014-06-20 09:18:54"
}
You can achieve the same result (JArray in JArray) using regular C# classes and at the end serialize to JSon.
I posted a sample in Github; here a fragment of the code that produces your expected output:
var Surveys = new List<SurveytrackD>();
Surveys.Add( new SurveytrackD { id = "26", appsurvey = "1", fk_curriculumid = "70", status = "Completed", learnerid = "240" } );
Surveys.Add( new SurveytrackD { id = "27", appsurvey = "1", fk_curriculumid = "71", status = "Completed", learnerid = "241" });
foreach (var survey in Surveys)
{
survey.questions = new List<Question>();
survey.questions.Add(new Question { questionid = "1", feedback = "0" });
survey.questions.Add(new Question { questionid = "2", feedback = "1" });
}
var json = JsonConvert.SerializeObject(Surveys, Formatting.Indented);
Console.WriteLine(json);
The output is:
[
{
"fk_clientid": null,
"learnerid": "240",
"appsurvey": "1",
"id": "26",
"fk_curriculumid": "70",
"status": "Completed",
"lastaccessedon": null,
"questions": [
{
"feedback": "0",
"questionid": "1"
},
{
"feedback": "1",
"questionid": "2"
}
]
},
{
"fk_clientid": null,
"learnerid": "241",
"appsurvey": "1",
"id": "27",
"fk_curriculumid": "71",
"status": "Completed",
"lastaccessedon": null,
"questions": [
{
"feedback": "0",
"questionid": "1"
},
{
"feedback": "1",
"questionid": "2"
}
]
}
]

Categories

Resources