Replace String with Array of Objects - c#

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

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 deserialize string to JObject without scientific notation in C#

I have a string like this:
var str = "{'data': {'someProperty': 0.00001}}";
When I parse it to JObject like that
var jObject = JObject.Parse(str);
My jObject looks like this:
{"data": {"someProperty": 1E-05}}
I need to get rid of scientific notation so that resulting JObject would look like original json.
I managed to do that using later version of Newtonsoft.Json like that:
var serializer = new JsonSerializer { FloatParseHandling = FloatParseHandling.Decimal };
using (System.IO.TextReader tr = new System.IO.StringReader(str)
using (var jsonReader = new JsonTextReader(tr))
{
var jp = serializer.Deserialize(jsonReader);
var jObject = JObject.FromObject(jp);
}
But I need to achieve the same result using Newtonsoft.Json version 3.5 which does not have a FloatParseHandling property. I guess I need to implement a JsonConverter somehow, but I have no idea how to do that, since my real json is much more complex than the one in example and I need to handle all the float values in it the right way.
So, what would be the right way to get a JObject without a scientific notation for float values using Newtonsoft 3.5?
Following produces the object you are looking for
JObject.Load(new JsonTextReader(new StringReader(str)) { FloatParseHandling = FloatParseHandling.Decimal }, null)
taken from here:
EDIT:
JTokenTypes in NewtonSoft v 3.5.8 are limited to Float and Integer (in regards to decimal). There is no decimal type in that version and thus makes it not possilbe to have a decimal value in that JObject.
JTokenTypes from v3 of newtonsoft
None = 0,
Object = 1,
Array = 2,
Constructor = 3,
Property = 4,
Comment = 5,
Integer = 6,
Float = 7,
String = 8,
Boolean = 9,
Null = 10,
Undefined = 11,
Date = 12,
Raw = 13,
Bytes = 14
The right way to do this would be to upgrade the Newtonsoft package :)
Jawad's provided code is not the best solution because it will end up in memory leaks. StringReader and JsonTextReader are both implementing the IDisposable interface and therefore must be disposed if they are not used anmyore.
Safer code would be:
public JObject CustomJObjectLoad(string str)
{
using (var stringReader = new StringReader(str))
{
using (var jsonReader = new JsonTextReader(stringReader) { FloatParseHandling = FloatParseHandling.Decimal })
{
return JObject.Load(jsonReader, null);
}
}
}
You can also create simple POCO object. and make sure someProperty is of type string and then de-serialize the json string
var myObject = Newtonsoft.Json.JsonConvert.DeserializeObject<YourObject>(json)
First, your json isn't valid :)
It should have double quotes:
{"data": {"someProperty": 0.00001}}
But even better, using standard casing, would be:
{"Data": {"SomeProperty": 0.00001}}
And then, we can do this:
var str = "{\"Data\": {\"SomeProperty\": 0.00001}}";
dynamic myObject = JsonConvert.DeserializeObject(str);
var val = myObject.Data.SomeProperty.ToString("0." + new string('#', 339));
val will then be: "0.00001"
(Note: I stole the solution from: Double to string conversion without scientific notation)

C# String to float with specific format

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

NewtonSoft JSON within strings serialization

Given a list of JSON strings is it possible to convert the List to JSON without the serializer thinking that the JSON strings are plain old strings. Using NewtonSoft .NET
Using:
List<string> list = { "{"foo": "bar"}", "[ 1, 2, 3]", "{"biz": "baz", "fiz": ["a", "b", "c"]}";
String json = JsonConvert.SerializeObject(list, Formatting.Indented);
at the current moment I get something like this from json:
"[ \n\r "{"foo": "bar"}", \n\r "[ 1, 2, 3]", ...]"
The serializer treats the json strings like any other strings that have special formatting.
I would like something more like this:
"[
{
"foo": "bar"
},
[
1,
2,
3
],
{
"biz": "baz",
"fiz": [
"a",
"b",
"c"
]
}
]"
something like that with proper indentation.
The idea here is to build the JSON yourself using the Json.NET API instead of writing it by hand. For this, you could use JToken to store your original json strings and then wrap the result inside a JArray. You can then use the ToString method to serialize everything back to JSON when you are done.
var finalString = new JArray(list.Select(JToken.Parse).ToArray()).ToString();
Use this:
JsonSerializer serializer = new JsonSerializer();
serializer.Formatting = Formatting.Indented;

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

Categories