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
Related
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);
I am going to generate Eway Bill API from below Request.The response of below request is showing fine in "Postmen" but at the same time when I execute this below request from C# Code then its shows an error message as "The remote server returned an error: (400) Bad Request.".
I would like to know how to show the postmen error message in C# Code.
URL :-
https://ewbbackend-preprodpub-http.internal.cleartax.co/gst/v0.1/taxable_entities/1c74ddd2-6383-4f4b-a7a5-007ddd08f9ea/ewaybill/GLD23985?activity_type=GENERATE_EWB
Header :-
Content-type : application/json
X-Cleartax-Auth-Token : b1f57327-96db-4829-97cf-2f3a59a3a548
taxable_entity_id : b1f57327-96db-4829-97cf-2f3a59a3a548
Body :-
{
"id": "GLD23985",
"transaction_date": "26/10/2020",
"source": "USER",
"document_number": "BQ/20/0251",
"type": "OUTWARD",
"transport_mode": "ROAD",
"dispatch_from_state": "HARYANA",
"sub_supply": "Supply",
"distance": "90",
"vehicle_number": "TN32N1049",
"document_type": "Tax Invoice",
"seller": {
"address1": "142/1,Trunk Road",
"address2": "Perumugai",
"city": "Via Vellore",
"gstin": "29AEKPV7203E1Z9",
"name": "K.H Exports India Private Limited",
"state": "HARYANA",
"zip_code": ""
},
"receiver": {
"address1": "4/74, VOC Street, Seenerkuppam Village, ",
"address2": "Poonamalle, Chennai 600 056",
"city": "",
"gstin": "33AAACR1714R1ZA",
"name": "KH EXPORTS INDIA PVT.LTD. (LGD)",
"state": "TAMIL NADU",
"zip_code": "600003"
},
"consignee": {
"city": "",
"state": "TAMIL NADU",
"zip_code": "600003"
},
"line_items": [
{
"cess_rate": "0",
"cess_val": "0",
"cgst_rate": "0",
"cgst_val": "0",
"description": "STYLE;91311 COLOUR;SVFD7 BELT & PA",
"gst_code": "4203",
"igst_rate": "28.00",
"igst_val": "16800.000000",
"item_code": "STYLE;91311 COLOUR;SVFD7 BELT & PA",
"quantity": "3.00",
"serial_number": "1",
"sgst_rate": "0",
"sgst_val": "0",
"taxable_val": "600.0000",
"unit_of_measurement": "NUMBERS"
},
{
"cess_rate": "0",
"cess_val": "0",
"cgst_rate": "0",
"cgst_val": "0",
"description": "STYLE;91307 COLOUR;ABFD2 BELT & PA",
"gst_code": "4203",
"igst_rate": "28.00",
"igst_val": "16800.000000",
"item_code": "STYLE;91307 COLOUR;ABFD2 BELT & PA",
"quantity": "3.00",
"serial_number": "2",
"sgst_rate": "0",
"sgst_val": "0",
"taxable_val": "600.0000",
"unit_of_measurement": "NUMBERS"
}
]
}
Response:-
{
"errors": {
"err_1": {
"code": "BAD_REQUEST_ATTR",
"message": "Pincode should have 6 digits.",
"error_group_code": 0,
"error_id": 0,
"severity": "ERROR"
}
},
"error_sources": {
"seller": {
"zip_code": {
"error_refs": [
"err_1"
]
}
}
}
}
C# Code:-
string DATA = JsonConvert.SerializeObject(tr, Newtonsoft.Json.Formatting.Indented);
using (var client = new WebClient())
{
client.Headers.Add("taxable_entities", ConfigurationManager.AppSettings["taxable_entities"]);
client.Headers.Add("X-Cleartax-Auth-Token", ConfigurationManager.AppSettings["auth-token"]);
client.Headers[HttpRequestHeader.ContentType] = "application/json";
string url = ConfigurationManager.AppSettings["host"] + ConfigurationManager.AppSettings["taxable_entities"] + "/ewaybill/" + TblHeader.Rows[0]["id"].ToString() + "?activity_type=GENERATE_EWB";
string res = client.UploadString(url, "PUT", DATA);
}
Hi my friend you can use this code to handle your respond and get your answer.
The previous examples return an HttpResponseMessage message from the controller action, but you can also use HttpResponseException to return an HttpError. This lets you return a strongly-typed model in the normal success case, while still returning HttpError if there is an error
public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var message = string.Format("Product with id = {0} not found", id);
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
}
else
{
return item;
}
}
I am using netownsoft json.net to serlize an object but its adding string at the start I dont under stand why its doing this.
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
public async Task<T> GetDataFromSageService<T>(string url, params string[] args)
where T : class
{
var uri = new Uri(string.Format(url, args));
var response = await _client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(content);
}
return default(T);
}
I am using the following to encode my end point which is hosted in a wcf service.
public string GetWarehouses()
{
DataSet ds = new SqlDa().GetWarehouses();
ds.Tables[0].TableName = "Warehouses";
return JsonConvert.SerializeObject(ds, Formatting.Indented);
}
But the string i am getting back is as such
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
{
"Warehouses": [
{
"WarehouseID": 13016489,
"Name": "B",
"Description": "Belfast "
},
{
"WarehouseID": 13016647,
"Name": "B",
"Description": "B"
},
{
"WarehouseID": 13815467,
"Name": "Direct Delivery",
"Description": ""
},
{
"WarehouseID": 1008,
"Name": "PW",
"Description": "Postal Way"
},
{
"WarehouseID": 13016234,
"Name": "H",
"Description": "Hospital"
},
{
"WarehouseID": 13016238,
"Name": "MPC",
"Description": "Clinic"
},
{
"WarehouseID": 13029366,
"Name": "O",
"Description": "Outpatient"
},
{
"WarehouseID": 13815466,
"Name": "Returns",
"Description": ""
}
]
}
</string>
As You can see its enclosed it as a string for some reason and don't understand as to why. Is their a way with the data set to make sure that it gets converted into proper json.
If you don't want to modify your server code, you could use regex to extract legal json string from your response.
string content ="your context with xml"
Regex regex = new Regex("<string\\s*xmlns=\".*\">([\\s\\S]*)</string>");
Match match = regex.Match(content);
Response.Write(match.Groups[1].Value);
Newtonsoft.Json.JsonConvert.DeserializeObject(match.Groups[1].Value);
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);
For my code I am using the Wikipedia API which provides links to all places that are linked with the Wikipedia article of that city. But with my code there are some extra unnecessary links. I want to only return links where the type is "landmark".
My Wikipedia API is:
https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Berlin&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json
Sample JSON data from the Wikipedia API:
"query": {
"geosearch": [
{
"pageid": 5858187,
"ns": 0,
"title": "Stuttgart Hauptbahnhof",
"lat": 48.783888888889,
"lon": 9.1816666666667,
"dist": 136.8,
"primary": "",
"type": "railwaystation",
"name": "",
"dim": 1000,
"country": "DE",
"region": "BW"
},
{
"pageid": 6102287,
"ns": 0,
"title": "Staatstheater Stuttgart",
"lat": 48.780277777778,
"lon": 9.185,
"dist": 361,
"primary": "",
"type": "landmark",
"name": "",
"dim": "900",
"country": "DE",
"region": "BW"
},
{
"pageid": 35806545,
"ns": 0,
"title": "Versatel building",
"lat": 48.78409,
"lon": 9.17799,
"dist": 400.4,
"primary": "",
"type": null,
"name": "",
"dim": 1000,
"country": null,
"region": null
},
{
"pageid": 3230957,
"ns": 0,
"title": "Neue Staatsgalerie",
"lat": 48.780277777778,
"lon": 9.1869444444444,
"dist": 430.6,
"primary": "",
"type": "landmark",
"name": "",
"dim": 1000,
"country": "DE",
"region": "BW"
},
....
]
}
My code to get the Title from this API.
using (var client = new HttpClient())
{
var response = client.GetAsync("https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Berlin&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json").Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
string responseString = responseContent.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<RootObject>(responseString).query.geosearch.Select(a => a.title).ToList();
foreach (var item in obj)
{
Console.WriteLine(item);
}
}
}
Here is the current output:
How can I get the title from the results where the type is "landmark"?
If you use JSON format, try this:
var obj = JsonConvert.DeserializeObject<RootObject>(responseString).query.geosearch
.Where(a => a.type == "landmark").Select(a => a.title).ToList();
Also you can get all titles without to use Json.NET. This is how I do it with XML format:
using (var webResponse = (HttpWebResponse)WebRequest.Create("https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Berlin&gslimit=500&gsprop=type&format=xml").GetResponse())
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
var response = XElement.Parse(reader.ReadToEnd());
var obj = response.Descendants("gs")
.Where(a => a.Attribute("type") != null && a.Attribute("type").Value == "landmark")
.Select(a => a.Attribute("title").Value).ToList();
}
}
I don't know C# :-)
But try something like this:
var geosearch = JsonConvert.DeserializeObject<RootObject>(responseString).query.geosearch;
var landmarks = geosearch.Where(type => type == "landmark");