How To String Format Complex Json Body in C# - 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);

Related

How can I convert these escape sequences back to their original characters?

JsonNode.Parse() seems to convert my < and > to the escape sequences \u003C and \u003E when they appear inside double-quotes "".
How can I convert these escape sequences back to their original characters?
This is my C# code:
using System.Text.Json.Nodes;
Console.WriteLine("JsonNode test");
var testString = "{ \"testString\" : \"<...>\" }";
Console.WriteLine($"{testString}, {testString.Length}");
var jsonNode = JsonNode.Parse(testString);
var jsonString = jsonNode.ToJsonString();
Console.WriteLine($"{jsonString}, {jsonString.Length}");
Output:
JsonNode test
{ "testString" : "<...>" }, 26
{"testString":"\u003C...\u003E"}, 32
I've tried the HtmlDecode and UrlDecode methods, but they are not right for this situation.
The json is still valid, but I usually always recommend to use Neftonsoft.Json since it has much much less problems, but you can use a string Replace as well
var jsonNode = JsonNode.Parse(testString);
var jsonString = jsonNode.ToJsonString().Replace("\\u003C","<").Replace("\\u003E",">");
result
{"testString":"<...>"}
another option is to use UnsafeRelaxedJsonEscaping, but it is not safe in some cases
var options = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
WriteIndented = true
};
var jsonString = System.Text.Json.JsonSerializer.Serialize(jsonNode, options);

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

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("$", ""));

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"}]"

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

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