Removing a field from jSon String - c#

I am storing jSon string as hexa-decimal or some characters string, its all working fine whan I retrieving as json string in my code, but there is one field I want to remove from the jSob object after I retrieved.
var t = StoredProcedures.SP_GlobalSearch.Execute(new SP_GlobalSearch_Params
{
Search = request.search,
SourceKey = "",
Skip = start,
Take = length,
ShowDeleted = false
}).Select(x => new SP_GlobalSearch
{
JsonObject = x.Data != null ? new JavaScriptSerializer().DeserializeObject(x.Data.Replace("", "")) : null,
Date = x.Date,
JsonObjectId = x.JsonObjectId,
SourceKey = x.SourceKey,
SourceId = x.SourceId,
TotalCount = x.TotalCount
});
var response = t?.ToList();
var jsondata = new DataTableResponse<SP_GlobalSearch>
{
totalCount = (int)response.Where(x => x.TotalCount != null).FirstOrDefault().TotalCount,
data = response.Where(x => x.TotalCount == null)
};
var jsonResult = Json(jsondata);
jsonResult.MaxJsonLength = Int32.MaxValue;
return jsonResult;
I am reading the text as jSon with the below statement,
JavaScriptSerializer().DeserializeObject(x.Data.Replace("", ""))
I want to remove the violations field from it, any help please. Thanks in advance
Here is my json:
{
"InspectionResultId":846,
"InspectionResultNumber":"T00846",
"InspectionRequestId":507,
"InspectionRequestNumber":"R00507",
"CaseId":689,
"InspectionResultStatusId":605,
"EnforcementSectionId":104,
"ViolationTypeId":603,
"DateOfInspection":"\/Date(1589439600000)\/",
"InspectionComment":"send to office staff, open investigation",
"InspectedCompanyDataId":964,
"ContactTypeId":701,
"EnteredById":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"InspectionResultTimestamp":"\/Date(1588280817470)\/",
"DateCreated":"\/Date(1588280817487)\/",
"DateUpdated":"\/Date(1588281867967)\/",
"CreatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"UpdatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"Case":{
"RelatedContactId":0,
"CaseId":689,
"CaseNumber":"I00689",
"IsInvestigation":true,
"CaseStatusId":801,
"InspectionItemSourceId":211,
"EnforcementSectionId":104,
"ReminderDate":"\/Date(1590044400000)\/",
"PreCaseSummary":"send to office staff, open investigation",
"AssignedToInspectorId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"CaseTimestamp":"\/Date(1588281867403)\/",
"CaseCompanyId":964,
"DateCreated":"\/Date(1588281867437)\/",
"DateUpdated":"\/Date(1588281867840)\/",
"CreatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"UpdatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"IsDeleted":false,
"InterpreterNeeded":false,
"VoluntaryDisclosure":false,
"PenaltyAdjustment":0,
"Company":{
"ContactId":964,
"ContactTypeId":1000,
"FirstName":"04.30.2020 new co",
"Notes":"new request",
"Active":true,
"Created":"\/Date(1588279909680)\/",
"Updated":"\/Date(1588279909680)\/",
"DateCreated":"\/Date(1588279909680)\/",
"DateUpdated":"\/Date(1588279909680)\/",
"IsEJArea":false,
"CreatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"UpdatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"Classification":{
},
"Class":"Company",
"IsSpecial":false,
"Address":{
"Street1":"5678 Street",
"City":"Sacramento",
"StateCode":"CA",
"Zip":"95812",
"Country":"0"
}
}
},
"InspectionResultStatus":{
"InspectionResultStatusId":605,
"InspectionResultStatusName":"Clean",
"InspectionResultStatusSortOrder":5
},
"EnforcementSection":{
"EnforcementSectionId":104,
"EnforcementSectionName":"STBES",
"EnforcementSectionSortOrder":0,
"BranchId":2
},
"InspectedCompanyData":{
"ContactId":964,
"ContactTypeId":1000,
"FirstName":"04.30.2020 new co",
"Notes":"new request",
"Active":true,
"Created":"\/Date(1588279909680)\/",
"Updated":"\/Date(1588279909680)\/",
"DateCreated":"\/Date(1588279909680)\/",
"DateUpdated":"\/Date(1588279909680)\/",
"IsEJArea":false,
"CreatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"UpdatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"Classification":{
},
"Class":"Company",
"IsSpecial":false
},
"InspectionItems":[
{
"InspectionItemId":1054,
"InspectionItemNumber":"T00000",
"InspectionRequestId":507,
"InspectionResultId":846,
"CaseId":689,
"InspectionItemSourceId":229,
"IsCreatedInCase":false,
"ShowYearMakeModel":"",
"ShowYearMakeModelVIN":"",
"GrossWeight":0.00,
"RegHoldSet":false,
"InspectionItemTimestamp":"\/Date(1588280802553)\/",
"DateCreated":"\/Date(1588280802567)\/",
"DateUpdated":"\/Date(1588281868153)\/",
"CreatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"UpdatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"Violations":[
]
}
],
"CompletedBy":[
{
"IsActive":true,
"FirstName":"Daphne",
"LastName":"Greene",
"ObjectGUID":"S-1-5-21-1538631513-416410304-3002070310-33442",
"NameLoginFormat":"dgreene",
"NameFirstLast":"Daphne Greene",
"NameLastFirst":"Greene Daphne",
"Email":"daphne.greene#arb.ca.gov",
"EmailConfirmed":false,
"SecurityStamp":"e061e77e-c93e-4b9e-8497-4852b5cb4ca2",
"PhoneNumberConfirmed":false,
"TwoFactorEnabled":false,
"LockoutEnabled":false,
"AccessFailedCount":0,
"Id":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"UserName":"dgreene"
}
],
"EnteredBy":{
"IsActive":true,
"FirstName":"Daphne",
"LastName":"Greene",
"ObjectGUID":"S-1-5-21-1538631513-416410304-3002070310-33442",
"NameLoginFormat":"dgreene",
"NameFirstLast":"Daphne Greene",
"NameLastFirst":"Greene Daphne",
"Email":"daphne.greene#arb.ca.gov",
"EmailConfirmed":false,
"SecurityStamp":"e061e77e-c93e-4b9e-8497-4852b5cb4ca2",
"PhoneNumberConfirmed":false,
"TwoFactorEnabled":false,
"LockoutEnabled":false,
"AccessFailedCount":0,
"Id":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"UserName":"dgreene"
},
"MyGridContacts":[
],
"CreatedByUser":{
"IsActive":true,
"FirstName":"Daphne",
"LastName":"Greene",
"ObjectGUID":"S-1-5-21-1538631513-416410304-3002070310-33442",
"NameLoginFormat":"dgreene",
"NameFirstLast":"Daphne Greene",
"NameLastFirst":"Greene Daphne",
"Email":"daphne.greene#arb.ca.gov",
"EmailConfirmed":false,
"SecurityStamp":"e061e77e-c93e-4b9e-8497-4852b5cb4ca2",
"PhoneNumberConfirmed":false,
"TwoFactorEnabled":false,
"LockoutEnabled":false,
"AccessFailedCount":0,
"Id":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"UserName":"dgreene"
},
"UpdatedByUser":{
"IsActive":true,
"FirstName":"Daphne",
"LastName":"Greene",
"ObjectGUID":"S-1-5-21-1538631513-416410304-3002070310-33442",
"NameLoginFormat":"dgreene",
"NameFirstLast":"Daphne Greene",
"NameLastFirst":"Greene Daphne",
"Email":"daphne.greene#arb.ca.gov",
"EmailConfirmed":false,
"SecurityStamp":"e061e77e-c93e-4b9e-8497-4852b5cb4ca2",
"PhoneNumberConfirmed":false,
"TwoFactorEnabled":false,
"LockoutEnabled":false,
"AccessFailedCount":0,
"Id":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
"UserName":"dgreene"
}
}
This above object is a dynamic object returned as string I want to remove Violation related fields and its values from it.
I want to remove the Violations, ViolationTypeId etc fields related to Violation from the jSon object above, can you please help me in this regards thank you.

You can simply convert it to object, remove the field and back to string.
for example in javascript
assuming your json is in variable myjson
tmp = Object(myjson.Data)
delete tmp.Violations
myjson.Data = JSON.stringify(tmp)
in C#, assuming Data is your string json
JObject tmp = JObject.Parse(Data);
tmp.Property("Violations").Remove();
Data = JavaScriptSerializer().Serialize(jsonResult.Data);

Related

'Accessed JObject values with invalid key value: 1. Object property name expected.'

I am trying to get JSON data from an api.
I have this json with me:
{
"elements": [
{
"id": 1,
"name": "Bob",
"address": "abc street",
"hobbies": {
"indoor": "Games, reading books",
"outdoor": ""
}
},
{
"id": 2,
"name": "Mark",
"address": "def street",
"hobbies": {
"indoor": "Games, reading books",
"outdoor": ""
}
}
]
}
I have this code with me:
using(var httpClient = new HttpClient()) {
HttpResponseMessage response = httpClient.GetAsync("api_url_here").Result;
var studentJsonString = response.Content.ReadAsStringAsync().Result;
var Jsresult = new JavaScriptSerializer().Deserialize<dynamic>(studentJsonString).ToString();
JObject jObject = JObject.Parse(Jsresult);
IEnumerable<dynamic> listDyn = jObject[0].Select(items => new StudentModel// gives error here as whole
{
id = items["id"].ToString(),
name = items["name"].ToString(),
address= items["address"].ToString()
});
}
But when I am calling the above method but it is giving me an error:
'Accessed JObject values with invalid key value: 1. Object property name expected.'
What am I missing?
Why are you deserializing twice? The result of
JavaScriptSerializer().Deserialize(customerJsonString)
is already an object. You don't need to parse it again with JObject.Parse(). You can just do
JObject jObject= JObject.Parse(customerJsonString)
Furthermore the result of JObject.Parse() is a dictionary and not an array. It has properties, which you can access by their names. For instance
jObject["elements"]
But of course, the compiler can't possibly predict, that jObject["elements"] will be an IEnumerable, so you will have to make sure of that.
jObject.Value<JArray>("elements").Select(item => ...)
This reads the property elements, of jObject as a JArray.

Using Dynamic and enforcing WCF contract upon Deserialization

I have two model classes IntroModel and PhonePageModel. These are both WCF contracts.
I'm calling an API that gives back JSON and lets say I have stored it in string format.
String myApiData = myAPI.getTodaysInfo();
Using a function enum parameter, I would like to deserialize into the correct type of model
IntroPageModel introPageModel = null;
PhonePageModel phonePageModel = null;
if (enumVal == myEnums.IntroPage)
{
introPageModel = JsonConvert.DeserializeObject<IntroPageModel>(myApiData);
}
else if (enumVal == myEnums.PhonePageModel)
{
phonePageModel = JsonConvert.DeserializeObject<PhonePageModel>(myApiData);
}
This leaves the problem later in my code though of checking which model isn't null to know which model to work with afterwards. Instead, could I use dynamic but still ensure the information from myApiData is validated properly based upon the correct WCF Page model?
dynamic myPageModel = null;
if (enumVal == myEnums.IntroPage)
{
myPageModel = JsonConvert.DeserializeObject<IntroPageModel>(myApiData);
}
else if (enumVal == myEnums.PhonePageModel)
{
myPageModel = JsonConvert.DeserializeObject<PhonePageModel>(myApiData);
}
Asuming that you your get todayinfo as result array than object it will be something like this:
[
[
{
"IntroModelid": 1,
"IntroModelname": "intro123",
"guid": "151512321312",
"introModelfunc": [
{
"funcid": 1,
"funcname": "func123"
}
]
}
],
[
{
"PhonePageModelid": 1,
"PhonePageModelname": "phone123",
"other": "other",
"phonenumers": [
{
"numersid": 1,
"numbers": 6789,
"status": "OK"
},
{
"numersid": 2,
"numbers": 12345,
"funcionamiento": "NO"
}
]
}
]
]
when you get your collection as this:
var myapidata = JsonConvert.DeserializeObject(myApiDataString);
you will have two ChildrenTokens = Count = 2
you can iterate this as you wish. Or you can pass to your class list
var myapidata = (JArray)JsonConvert.DeserializeObject(json);
var IntroPageModel = myapidata [0];
var PhonePageModel = myapidata [1];
Hope you find useful

Serialize list of dictionaries into accepted DataTable Ajax object

I have a web application in which I'm retrieving some data into bootstrap table, what i want to do now is to use jQuery DataTable instead of the current as it has too much useful features.
Currently I'm retrieving the data from the server side using OOP approach, where a class object represents a data row in a particular table, and this object includes a dictionary which stores column names and values.
What I'm doing now is that I'm retrieving these class objects and append each dictionary of each object in a List<Item> and then serialize this list using JavaScriptSerializer object, and this object returns the following JSON format:
[
{
"slno":"2",
"status_message":"Lights still flashing",
"crm_services_id":"1", "subject_id":"Lights are flashing",
"severity_id":"5",
"user_id":"husain.alhamali",
"status_id":"1"
},
{
"slno":"3",
"status_message":"lights working fine",
"crm_services_id":"2",
"subject_id":"Lights are flashing",
"severity_id":"3",
"user_id":"husain.alhamali",
"status_id":"2"
}
]
When i tried to use this object to fill my DataTable AJAX I've got an error says:
Invalid JSON response
I saw some examples of a valid JSON response that is acceptable to a DataTable which is as follow:
{
"data": [
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$320,800"
],
[
"Garrett Winters",
"Accountant",
"Tokyo",
"8422",
"2011/07/25",
"$170,750"
]
}
Now my question is is there any tool or plugin that could re-format my JSON string into an acceptable format like the one above?
With this HTML:
<table id="example"></table>
This JS will create a table:
var data = [{
"slno": "2",
"status_message": "Lights still flashing",
"crm_services_id": "1",
"subject_id": "Lights are flashing",
"severity_id": "5",
"user_id": "husain.alhamali",
"status_id": "1"
}, {
"slno": "3",
"status_message": "lights working fine",
"crm_services_id": "2",
"subject_id": "Lights are flashing",
"severity_id": "3",
"user_id": "husain.alhamali",
"status_id": "2"
}];
function getColumns(){
for(var i = 0; i < data.length; i++){
let columnsArray = [];
var keys = Object.keys(data[i]);
for(k in Object.keys(data[i])){
if(data[i].hasOwnProperty(keys[k])){
columnsArray.push({
"data":keys[k]
});
}
}
return columnsArray;
}
}
$(document).ready(function() {
var table = $('#example').DataTable({
"columns": getColumns(),
"data": data
});
});
Working example. Hope that helps.
dataTable require json data in return from ajax response having following keys
1. data
2. draw
3. recordsTotal
4. recordsFiltered
Use this:
var data = list.Select(u => u.GetType()
.GetProperties()
.Select(p => p.GetValue(u, null)));
example
public class User
{
public int userId { get; set; }
public string name { get; set; }
}
public class Programm
{
static void Main()
{
var list = new List<User>();
list.Add(new User
{
userId = 1,
name = "name 1",
});
list.Add(new User
{
userId = 2,
name = "name 2",
});
var data = list.Select(u => u.GetType()
.GetProperties()
.Select(p => p.GetValue(u, null)));
Console.WriteLine(new JavaScriptSerializer().Serialize(new
{
data = data
}));
}
}
result
{
"data" : [
["1", "name 1"],
["2", "name 2"]
]
}

Converting "[myObject][1][application]" string to useable path on JObject

First let me start off by showing you what I am trying to accomplish by using pseudo code. (Yes I know this example is not possible)
var path = "[DocInfo][Type]";
var doc = couchDbCall();
var specificProperty = doc[path];
I want to turn a string into a literaly path accessor in code but cannot seem to find any examples etc; probably due to my lack of a good search query.
{
"_id": "bb9f9e13-218a-4403-9920-79b0d353634b",
"_rev": "2-908d1257d7324a8b6f1c333cbefe2e41",
"Name": "conversionTest2",
"DocInfo": {
"Type": "Application",
"Platform": "test",
"Version": "12",
"VersionRelId": -1,
"Category": "Communications and Messaging",
"Created": {
"CreatedDate": "3/19/2015 7:56:07 PM",
"User": {
"Id": "bf51f6ce-d3f7-46ff-9ff0-c1e60c2ded44",
"Name": "Adrian Campos",
"Email": "adrian.campos#bizdox.com"
}
},
"Template": "Other Application",
"TemplateVersion": 0
}
}
Example with JSON.Net (get it via NuGet):
dynamic o = JsonConvert.DeserializeObject(yourJsonString);
string type = o.DocInfo.Type; // gets "Application"
var doc = couchDbCall();
var specificProperty = doc[type]; // assuming doc takes a string as key
UPDATE:
that works also:
string type = o["DocInfo"]["Type"];
UPDATE 2:
as far as I understand this little recursive method will help you out (note that there's no error handling whatsoever):
private string DoMyPaths(List<string> paths, JToken token)
{
string s = paths[0];
if (paths.Count > 1)
{
paths.RemoveAt(0);
JToken result = token[s];
return DoMyPaths(paths, result);
}
return token[s].ToString();
}
now you can pass in your path (delimited by '.'):
string myPath = "DocInfo.Created.User.Name";
var paths = myPath.Split('.').ToList();
dynamic o = JsonConvert.DeserializeObject(json);
var result = DoMyPaths(paths, o);
result:
"Adrian Campos"

Convert JSON String to JSON Object c#

I have this String stored in my database:
str = "{ "context_name": { "lower_bound": "value", "upper_bound": "value", "values": [ "value1", "valueN" ] } }"
This string is already in the JSON format but I want to convert it into a JObject or JSON Object.
JObject json = new JObject();
I tried the json = (JObject)str; cast but it didn't work so how can I do it?
JObject defines method Parse for this:
JObject json = JObject.Parse(str);
You might want to refer to Json.NET documentation.
if you don't want or need a typed object try:
using Newtonsoft.Json;
// ...
dynamic json = JsonConvert.DeserializeObject(str);
or try for a typed object try:
using Newtonsoft.Json;
// single
Foo foo = JsonConvert.DeserializeObject<Foo>(str);
// or as a list
List<Foo> foos = JsonConvert.DeserializeObject<List<Foo>>(str);
This works
string str = "{ 'context_name': { 'lower_bound': 'value', 'pper_bound': 'value', 'values': [ 'value1', 'valueN' ] } }";
JavaScriptSerializer j = new JavaScriptSerializer();
object a = j.Deserialize(str, typeof(object));
there's an interesting way to achive another goal which is to have a strongly type class base on json with a very powerfull tools that i used few days ago for first time to translate tradedoubler json result into classes
Is a simple tool: copy your json source paste and in few second you will have a strongly typed class json oriented .
In this manner you will use these classes which is more powerful and simply to use.
You can try like following:
string output = JsonConvert.SerializeObject(jsonStr);
This works for me using JsonConvert
var result = JsonConvert.DeserializeObject<Class>(responseString);
If your JSon string has "" double quote instead of a single quote ' and has \n as a indicator of a next line then you need to remove it because that's not a proper JSon string, example as shown below:
SomeClass dna = new SomeClass ();
string response = wc.DownloadString(url);
string strRemSlash = response.Replace("\"", "\'");
string strRemNline = strRemSlash.Replace("\n", " ");
// Time to desrialize it to convert it into an object class.
dna = JsonConvert.DeserializeObject<SomeClass>(#strRemNline);
In a situation where you are retrieving a list of objects of a certain entity from your api, your response string may look like this:
[{"id":1,"nome":"eeee","username":null,"email":null},{"id":2,"nome":"eeee","username":null,"email":null},{"id":3,"nome":"Ricardo","username":null,"email":null}]
In this situation you may want an array of Jason objects and cycle through them to populate your c# variable. I've done like so:
var httpResponse = await Http.GetAsync($"api/{entidadeSelecionada}");
List<List<string[]>> Valores = new();
if (httpResponse.IsSuccessStatusCode)
{
//totalPagesQuantity = int.Parse(httpResponse.Headers.GetValues("pagesQuantity").FirstOrDefault());
//Aqui tenho que colocar um try para o caso de ser retornado um objecto vazio
var responseString = await httpResponse.Content.ReadAsStringAsync();
JArray array = JArray.Parse(responseString);
foreach (JObject objx in array.Children<JObject>())
{
List<string[]> ls = new();
foreach (JProperty singleProp in objx.Properties())
{
if (!singleProp.Name.Contains("_xyz"))
{
string[] val = new string[2];
val[0] = singleProp.Name;
val[1] = singleProp.Value.ToString();
ls.Add(val);
}
}
Valores.Add(ls);
}
}
return Valores;
I achieved this solution by the #Andrei answer.
This does't work in case of the JObject this works for the simple json format data. I have tried my data of the below json format data to deserialize in the type but didn't get the response.
For this Json
{
"Customer": {
"id": "Shell",
"Installations": [
{
"id": "Shell.Bangalore",
"Stations": [
{
"id": "Shell.Bangalore.BTM",
"Pumps": [
{
"id": "Shell.Bangalore.BTM.pump1"
},
{
"id": "Shell.Bangalore.BTM.pump2"
},
{
"id": "Shell.Bangalore.BTM.pump3"
}
]
},
{
"id": "Shell.Bangalore.Madiwala",
"Pumps": [
{
"id": "Shell.Bangalore.Madiwala.pump4"
},
{
"id": "Shell.Bangalore.Madiwala.pump5"
}
]
}
]
}
]
}
}
string result = await resp.Content.ReadAsStringAsync();
List<ListView11> _Resp = JsonConvert.DeserializeObject<List<ListView11>>(result);
//List<ListView11> _objList = new List<ListView11>((IEnumerable<ListView11>)_Resp);
IList usll = _Resp.Select(a => a.lttsdata).ToList();
// List<ListViewClass> _objList = new List<ListViewClass>((IEnumerable<ListViewClass>)_Resp);
//IList usll = _objList.OrderBy(a=> a.ReqID).ToList();
Lv.ItemsSource = usll;

Categories