C# String to float with specific format - c#

I'm trying to convert a string that is in the following format: 30,500 to convert to a float as 30.500 (in a json) So currently I have something like float.Parse(string.Format("{0:00,000}", inp_km.Text), CultureInfo.InvariantCulture.NumberFormat), but when I save it in json, it saves as 30500.00.
What am I doing wrong here?
How I just make it;
I make an object from the class Results like here;
team_results = new Results()
{
team_number = selected_team.team_number,
results = new Result[2] { new Result{ }, new Result { } }
};
Now when I add the new value to the json (example below) the input I get is 30,500
[
{
"team_number": 101,
"results": [
{
"given_start_time": "20:25",
"connection_to_start": "0:00",
"start_kp": "20:26",
"stop_kp": "0:0",
"missed_controls": 0,
"km": 0.000,
"gtks": [ "25:00", "30:15", "0:00" ]
},
{
"given_start_time": "21:56",
"connection_to_start": "0:00",
"start_kp": "21:57",
"stop_kp": "0:0",
"missed_controls": 0,
"km": 0.000,
"gtks": [ "25:00", "30:15" ]
}
]
}
]
But when it saves, it saves it as 30500.00

You are trying to execute Format on a string which will just yield the same string as a result.
You want to parse the string and pass an IFormatProvider implementation to the Parse method that "understands" what , and . mean in the string representation of the number being parsed.
In the example below I used the culture nl-NL which has the same meaning as what you expect in your question (. for separating thousands and , for separating the fractional part of the number).
const string inputText = "30,500";
var result = float.Parse(inputText, NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.GetCultureInfo("nl-NL"));
Console.WriteLine("Parsed {0} to value {1}", inputText, result);

You can create custom NumberFormatInfo
var nf = new System.Globalization.NumberFormatInfo();
nf.NumberDecimalSeparator = ",";
nf.NumberGroupSeparator = " ";
and use it to Parse numeric value
Console.WriteLine(float.Parse("30,5000", nf));

Well , I have a solution but it would not be the best but it will work .
as you are working on a string you can use this function
string converter(string s)
{
s = s.Replace('.',',');
return s;
}
also check this link
https://msdn.microsoft.com/en-us/library/czx8s9ts(v=vs.110).aspx

Related

Replace String with Array of Objects

I am trying to replace a string constant with an array of object.
What I have is
string test = "{\"property\":\"#replacedValue#\"}";
var array = someObject.where(x=>something).ToArray();
test = test.Replace("#replacedValue#",JsonConvert.SerializeObject(array));
output is coming as
{"property":"[{"name":"value"},{"name":"value"},{"name":"value"}]"}
Array is being replaced as string
what I want is
{"property":[{"name":"value"},{"name":"value"},{"name":"value"}]};
I am using .net core 3.1
You can parse your json string into JObject and replace property value:
string test = #"{""property"":""#replacedValue#""}";
var jObj = JsonConvert.DeserializeObject<JObject>(test);
jObj["property"] = new JArray(new[] {1,2,3,4});
Console.WriteLine(jObj.ToString());
will print:
{
"property": [
1,
2,
3,
4
]
}

How to read JSON into a JObject when the string contains double quotes ?

I have a piece of JSON that I want to get into a string for C# to use. The problem is when I escape all the double quotes it seems no longer valid. For example:
string jsonString = " {[ { \"FieldId\": \"Fields.364\", \"FieldName\": \"LoanNo\", \"Precision\": \"0\" } , { \"FieldId\": \"Fields.4002\", \"FieldName\": \"LastNameB\" } ]}";
JObject jsettings = JObject.Parse(jsonString);
Is there a easier way to get a string of JSON into a C# JObject?
You're not actually escaping any of the double quotes, as far as the JSON is concerned - the string doesn't contain any backslashes. You can confirm that with Console.WriteLine(jsonString);.
The problem is that you've currently got an array directly inside an object - that's not valid JSON.
If you change it so that the array is a property, it's fine:
string jsonString = " { \"foo\":[ { /* rest as before */ } ] }";
That ended up as JSON of:
{
"foo": [
{
"FieldId": "Fields.364",
"FieldName": "LoanNo",
"Precision": "0"
},
{
"FieldId": "Fields.4002",
"FieldName": "LastNameB"
}
]
}
(Just using Console.WriteLine(jsettings); after the code you'd posted.)

Store Hardcoded JSON string to variable

I'm having an issue storing this json string to a variable. It's gotta be something stupid I am missing here
private string someJson = #"{
"ErrorMessage": "",
"ErrorDetails": {
"ErrorID": 111,
"Description": {
"Short": 0,
"Verbose": 20
},
"ErrorDate": ""
}
}";
You have to escape the "'s if you use the # symbol it doesn't allow the \ to be used as an escape after the first ". So the two options are:
don't use the # and use \ to escape the "
string someJson = "{\"ErrorMessage\": \"\",\"ErrorDetails\": {\"ErrorID\": 111,\"Description\":{\"Short\": 0,\"Verbose\": 20},\"ErrorDate\": \"\"}}";
or use double quotes
string someJson =#"{""ErrorMessage"": """",""ErrorDetails"": {""ErrorID"": 111,""Description"": {""Short"": 0,""Verbose"": 20},""ErrorDate"": """"}}";
First things first, I'll throw this out there: It's for this reason in JSON blobs that I like to use single quotes.
But, much depends on how you're going to declare your string variable.
string jsonBlob = #"{ 'Foo': 'Bar' }";
string otherBlob = #"{ ""Foo"": ""Bar"" }";
...This is an ASCII-encoded string, and it should play nicely with single quotes. You can use the double-double-quote escape sequence to escape the doubles, but a single quote setup is cleaner. Note that \" won't work in this case.
string jsonBlob = "{ 'Foo': 'Bar' }";
string otherBlob = "{ \"Foo\": \"Bar\" }";
...This declaration uses C#'s default string encoding, Unicode. Note that you have to use the slash escape sequence with double quotes - double-doubles will not work - but that singles are unaffected.
From this, you can see that single-quote JSON literals are unaffected by the C# string encoding that is being used. This is why I say that single-quotes are better to use in a hardcoded JSON blob than doubles - they're less work, and more readable.
Simple Approach is to copy the JSON to a .json file and read that file in the code
string jsonData = string.Empty;
jsonData = File.ReadAllText(#"\UISettings.json");
Writing JSON inline with c# in strings is a bit clunky because of the double quotes required by the JSON standard which need escaping in c# as shown in the other answers. One elegant workaround is to use c# dynamic and JObject from JSON.Net.
dynamic message = new JObject();
message.ErrorMessage = "";
message.ErrorDetails = new JObject();
message.ErrorDetails.ErrorId = 111;
message.ErrorDetails.Description = new JObject();
message.ErrorDetails.Description.Short = 0;
Console.WriteLine(message.ToString());
// Ouputs:
// {
// "ErrorMessage": "",
// "ErrorDetails": {
// "ErrorID": 111,
// "Description": {
// "Short": 0
// .....
See https://www.newtonsoft.com/json/help/html/CreateJsonDynamic.htm.
I had this same problem I ended up writing an open source online converter that takes a JSON string and spits out the C# excaped string with the double quotes syntax. So
{ "foo":"bar"}
will be escaped into
var jsonString = #"{ ""foo"":""bar""}";
https://json-to-c-sharp.ndolestudio.com
https://github.com/AchoArnold/json-to-c-sharp
Starting from C# 11 supported on .NET 7, it's possible to embed a JSON string without any modification by enclosing it in triple quote characters, a feature called Raw string literal (learn.microsoft.com). Related useful language feature is StringSyntaxAttribute that allows Visual Studio to recognize the string variable is a JSON string and highlight any typos. A sample:
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
internal class Program
{
[StringSyntax(StringSyntaxAttribute.Json)]
private const string myCountry = """{"Name": "Slovakia", "CountryCode": 421}""";
private static void Main(string[] args)
{
var _ = JsonSerializer.Deserialize<Country>(myCountry);
}
class Country
{
public string Name { get; set; } = default!;
public int CountryCode { get; set; }
}
}
A Put the cart before the horse solution would be to serialize a anonymous class into a string:
var someJson = JsonConvert.SerializeObject(
new
{
ErrorMessage = "",
ErrorDetails = new
{
ErrorID = 111,
Description = new
{
Short = 0,
Verbose = 20
},
ErrorDate = ""
}
});
If you are using Visual Studio, then Select the whole JSON string then crtl+f to find the double quotes in the selection and then replace " with ""

Unable to Parse this Json string in c#

I tried using Newtonsoft.Json to deserialize this json string, but I'm not getting the desired output.
my json string is
[
{
"id": 1,
"key": "Residential Homeowner",
"i18nText": "unknown message code DB_ENUM_UserType_residentialhomeowner",
"i18nKey": "DB_ENUM_UserType_residentialhomeowner"
},
{
"id": 8,
"key": "VAR Dealer \/ Builder",
"i18nText": "unknown message code DB_ENUM_UserType_vardealer\/builder",
"i18nKey": "DB_ENUM_UserType_vardealer\/builder"
},
{
"id": 2,
"key": "Administrator",
"i18nText": "unknown message code DB_ENUM_UserType_administrator",
"i18nKey": "DB_ENUM_UserType_administrator"
},
{
"id": 9998,
"key": "TempGuidUser",
"i18nText": "unknown message code DB_ENUM_UserType_tempguiduser",
"i18nKey": "DB_ENUM_UserType_tempguiduser"
},
{
"id": 9999,
"key": "GuidUser",
"i18nText": "unknown message code DB_ENUM_UserType_guiduser",
"i18nKey": "DB_ENUM_UserType_guiduser"
}
]
I just want the value of key when value of id=1. Generally json starts with {}(curly bracket) but here it is like [](square bracket). I've seen many examples but none worked for me.
Generally json starts with {} (curly bracket), but here it is like [] (square bracket).
This is because you got an array of objects, not a single object. Arrays are serialized with square brackets around them. You should deserialize it into an array, and then grab the object at the index of interest.
This is a related post that addresses JSON parsing in C#: C# JSON Parsing.
If the brackets are a problem, simply use:
string json = inputJson.Trim().Trim('[',']');
If the id can have a minimum value of 1, then this should work:
string GetKey(string inputJson)
{
string key = inputJson.Substring(inputJson.IndexOf("key")+5);
key = key.Substring(key.IndexOf("\""), key.IndexOf(",")-key.IndexOf("\""));
key = key.Trim('\"');
return key;
}
If you are only interested in a single value from that larger JSON value, you may want to try Linq to JSON which would allow you to query over the JSON without deserializing everything.
Example:
JArray values = JArray.Parse(json);
string key;
var keyObject = values.FirstOrDefault(p => (int)p["id"] == 1);
if (keyObject != null)
{
key = (string)keyObject["key"];
}
[] is to define a json object array. Your output should be an array. Traverse through the array like:
for(var i=0; i<output.Length; i++)
{
if(output[i].id == "1") // desired id
{
Console.WriteLine(output[i].key);// use it as you wish
}
}
and use the found objects key.

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);
}

Categories