C# | Grabbing JSON from URL cannot convert string to int - c#

I have a piece of code, which should grab info from a URL. Get the value called lowest_price and then parse it into a variable, but there is a $ sign in the JSON so I had to remove it and after that I can't Parse the JSON correctly.
My code:
var tokenPrice = JObject.Parse(steamMarket).ToString().Replace("$", " ");
double marketPrice = tokenPrice["lowest_price"];
JSON
{"success":true,"lowest_price":"$5.61","volume":"6","median_price":"$5.61"}
Error:
Argument 1: cannot convert from 'string' to 'int'

double marketPrice = double.Parse(JObject.Parse(steamMarket)["lowest_price"].ToString().Replace("$", ""));

You can also do:
string json = "{\"success\":true,\"lowest_price\":\"$5.61\",\"volume\":\"6\",\"median_price\":\"$5.61\"}";
var jObject = Newtonsoft.Json.Linq.JObject.Parse(json);
double tokenPrice = double.Parse((string )jObject["lowest_price"], NumberStyles.Currency, new CultureInfo("en-US"));

tokenPrice["lowest_price"] is a string and c# will not automatically convert types for you.
var tokenPrice = JObject.Parse(steamMarket);
double marketPrice = double.Parse(tokenPrice["lowest_price"].ToString().Replace("$", ""));

Related

How To String Format Complex Json Body in C#

i have the following code
var UUID = "ExampleX";
var NumID = "ExampleY";
var Payload = string.Format("{\"API1\":{\"API2\":\"API3\",\"API4\":5},\"API6\":\"{0}\",\"API7\":\"{1}\",\"API8\":\"API8\"}",UUID,NumID);
i'm trying to replace the input for {0} and {1} with UUID and NumID but i kept getting the following Error
Input string was not in a correct format.
i'm still learning how to code any help is appreciated
You could parse the Json String as JObject and then replace the API6 and API7 values. For example,
var json = "{\"API1\":{\"API2\":\"API3\",\"API4\":5},\"API6\":\"{0}\",\"API7\":\"{1}\",\"API8\":\"API8\"}";
var jo = JObject.Parse(json);
jo["API6"] = UUID;
jo["API7"] = NumID;
var Payload = jo.ToString();
Output
{
"API1": {
"API2": "API3",
"API4": 5
},
"API6": "ExampleX",
"API7": "ExampleY",
"API8": "API8"
}
You have to escape the json brackets with double brackets so they are not interpreted as a placeholder:
var Payload = string.Format("{{\"API1\":{{\"API2\":\"API3\",\"API4\":5}},\"API6\":\"{0}\",\"API7\":\"{1}\",\"API8\":\"API8\"}}",UUID,NumID);

How to convert or serialized data to Json format in c#?

Am using following code to convert data to Json and return value is:
"{\"BillNo\":18}" . But i want to return value for key and value pair Like: {"BillNo":18}
public String Get()
{
var MaxBillNo = db.Billings.Max(b => b.BillNo.Substring(9, 5));
int i = Int32.Parse(MaxBillNo);
BillNumber billNumber = new BillNumber();
billNumber.BillNo = i;
string json = JsonConvert.SerializeObject(billNumber);
return json;
}
"{\"BillNo\":18}" is valid json string will be parsed in javascript on client side but not {"BillNo":18}
var myJson = "{\"BillNo\":18}";
console.log(JSON.parse(myJson));
Unfortunately it is not possible. It is standard C# string formatting rules.
\" is a double quotation mark. See Escape Sequences: https://msdn.microsoft.com/en-us/library/h21280bw.aspx
It is possible in C# but for that you have to pass a list of objects to serialize method. Here is the sample given below, hope so it will be helpful for you.
SmaccLib smacclib = new SmaccLib();
smaccDate = smacclib.Date_SaveFormat(date);
List<EmployeeAbsents> listEmployeeAbsents = _hrManager.EmployeeAbsentManager.SelectEmployeeAbsentsByDate(smaccDate, rowIndex);
if (listEmployeeAbsents != null && listEmployeeAbsents.Count > 0)
{
return JsonConvert.SerializeObject(listEmployeeAbsents);
}
return string.Empty;
And you result will be something like this.
"[{"EmployeeAbsentID":"81e930bb-a38e-4b85-ba6c-9cbd6e706872","EmployeeCode":"20","EmployeeName":"Bilal","AbsentDate":"11/09/2016","AbsentTypeCode":"10","AbsentTypeName":"Casual","IsDeductable":true,"Remarks":"re","EntryFrom":0,"RowIndex":4,"OperatingUserID":0,"RecordTimeStamp":"2016-02-19T13:20:44.417"}]"

show string in a desire format

I want to show my string in a special format.
For example I have a string like this s = "00012345"; and want to show it in this format 000(123-45)
I use this code for it:
label1.text = string.format("{0,###(###-##)}",s);
But just see this for result: 00012345.
What string formatting should I be using?
As mentioned you can't format an already existing string. First you need to convert the string to an int:
int num = Int32.TryParse(s);
Then you can do the formatting whilst converting it back into a string:
label1.text = num.ToString("000(000-00)");
string s = "00012345";
string s1 = s.Substring(0,3);
string s2 = s.Substring(3,3);
string s3 = s.Substring(6);
s = string.Format("{0}({1}-{2})", s1,s2,s3);

Json.Net parsing datetime value error

I am trying to convert a json string to a JObject using JObject.Parse, but running into the error "Error parsing positive infinity value. Path 'Modified.Date', line 1, position 52."
Here is the part of json that is throwing the error on -
{ ..., "Modified" : { "Date" : ISODate("2013-02-21T22:23:57.118Z"), "User" : "Admin" }, ...}
Here is the code I am using to do the parse -
var jobj = JObject.Parse(formJson)
Update: The json was generated by using mongodb's .ToJson() extension method, by sending in the following jsonwritersettings it generated json that was parsable by json.net - new JsonWriterSettings { OutputMode = JsonOutputMode.JavaScript };
I think you need to lose the ISODate.
This works:
String MyJson = "{MyDate : \"2013-02-21T22:23:57.118Z\" }";
var x = Newtonsoft.Json.Linq.JObject.Parse(MyJson);
I tried using Regex and convert in C#:
Regex _regex = new Regex(#"\d\d\d\d-\d\d-\d\d");
Match _date = _regex.Match(<Your_Date_String>);
if (_date.Success)
{
var datetime = Convert.ToDateTime(_date.Value);
}

How to convert a string with a period character to an int?

How do you convert a string with a period character to an int?
I have to convert strings like "1924.912" to int's, but the int.Parse() and Convert.ToInt32() methods don't work here.
Try this:
var str = "1924.912";
var mass = str.Split('.').Select(x => x).ToArray();
Or this:
var str = "1924.912";
var mass = str.Split('.');
To have all decimal like int use next:
var str = "1924.912";
var mass = str.Replace(".","");
You can use Double.Parse() and then convert result to int.
var result = (int)Double.Parse("1924.912");
Optionally you can specify decimal separator because its local specific.
If you want get 1924912 from "1924.912" you can achieve this by replacing "." by "":
string s = "1924.912";
int result = int.Parse(s.Replace(".", ""));
result.Dump();
Will print 1924912.
Do this
string value = "34690.42724";
Convert.ToInt64(Math.Round(Convert.ToDouble(value)));
double.Parse(textBox1.Text.Replace(".",","))
If you want to convert the string "1924.912" to the integer 1924912 disregarding the period you can use this expression where you simply remove any periods in the string before doing the conversion:
Int32.Parse("1924.912".Replace(".", String.Empty))

Categories