I have this method in which I'm trying to create JSON string:
//my current file
using Newtonsoft.Json;
string key1 = "FirstKey";
string key2 = "SecondKey";
string key3 = "ThirdKey";
private string CreateJson(string val1, string val2, string val3,string val4, string val5, string val6)
{
//process the six arguments and three key-related member variables to create a JSON array
//don't want to use JsonConvert.SerializeObject the way I'm doing below as it requires creating a class
var configs = new List<CustomClass>
{ new CustomClass{ FirstKey = val1,SecondKey= val2,ThirdKey= val3}
, new CustomClass{ FirstKey= val4,SecondKey= val5,ThirdKey = val6}
};
var jsonData = JsonConvert.SerializeObject(configs);
return jsonData;
}
//A class in another file
public class CustomClass
{
public string FirstKey { get; set; }
public string SecondKey{ get; set; }
public string ThirdKey{ get; set; }
}
I'm trying to create the JSON array using JSON.Net. The expected output is as below:
[{"FirstKey":val1,"SecondKey":val2,"ThirdKey":val3}
, {"FirstKey":val4,"SecondKey":val5,"ThirdKey":val6}]
Here val1
to val6
values should get replaced by the argument values at run-time.
Initially, since there were just three types of string key-value pairs, so I thought it would be pretty straightforward to create a JSON string simply by using string literals and appending then one after the other in JSON format. But soon I stumbled upon the world of escape characters which can deform a JSON string e.g. \r
.
I had been using JSON.Net library in the past simply to serialize and deserialize objects using JSONConvert
class and I never cared and was completely unaware about this handling of escape characters by JSON.Net library does behind the scene for us to keep the JSON string valid.
Anyways, coming back to my problem. I was able to solve my problem by creating a custom class having three properties FirstKey
, SecondKey
, and ThirdKey
. Then, create an object of the class, then assign the values in arguments val1
and val2
to then and then use JsonConvert.SerializeObject
API.
I want a very simply way of creating JSON string using JSON.Net NuGet package without involving custom classes. Creating a class CustomClass
altogether feels like an overhead here. I'm looking for something of sort of like StringBuilder.Append
API if it is available in the JSON library I'm using. I'm not sure if I'm missing any of the APIs in JSON.Net.
As mentioned in the comments, you could just as easily have created it using anonymous objects.
private string CreateJson(string val1, string val2, string val3, string val4, string val5, string val6) {
var configs = new[]
{
new { FirstKey = val1, SecondKey = val2, ThirdKey = val3},
new { FirstKey = val4, SecondKey = val5, ThirdKey = val6}
};
var jsonData = JsonConvert.SerializeObject(configs);
return jsonData;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With