Pass Variable in Json String in C#

Pass variable in JSON string in C#

Well you can concate the variable like

   string json =@"{  
'EmployeeName':" + name +",
'EmployeeID': '123',
}"

You can as well consider using string.Format() for this purpose and in C# 6 you can use variable interpolation syntax like

   string json =$"{  
'EmployeeName': {name} ,
'EmployeeID': '123',
}"

How to pass Json string with variable in c#?

string a = "a";
string b = "b";

string jSonContent = (@"{""fields"":{""summary"":""summary"" , ""description"": ""modified.""}}").Replace(@":""summary""", a).Replace("modified.", b);

Passing variables into a string variable that contains json

Rather then using the $ (string interpolation), you could consider converting the query-string into a class:

{
"size": 1000,
"query": {
"bool": {
"should": [
{
"match": {
"level": "Information"
}
},
{
"match": {
"level": "Error"
}
}
],
"filter": [
{
"range": {
"@timestamp": {
"gte": "2021-07-26T07:58:45.304-05:00",
"lt": "2021-07-26T08:58:45.305-05:00"
}
}
}
],
"minimum_should_match": 1
}
}
}

Which could be converted to something like this:

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
public class Match
{
public string level { get; set; }
}

public class Should
{
public Match match { get; set; }
}

public class Timestamp
{
public DateTime gte { get; set; }
public DateTime lt { get; set; }
}

public class Range
{
[JsonProperty("@timestamp")]
public Timestamp Timestamp { get; set; }
}

public class Filter
{
public Range range { get; set; }
}

public class Bool
{
public List<Should> should { get; set; }
public List<Filter> filter { get; set; }
public int minimum_should_match { get; set; }
}

public class Query
{
public Bool @bool { get; set; }
}

public class Root
{
public int size { get; set; }
public Query query { get; set; }
}

You can instanciate a new object from Root, and then add as many Matches to Should as you need, something similar like this:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Program
{
public static void Main()
{
Root queryObject = new();
queryObject.query.@bool.should.Add(
new Should() {
match = new() {
level = "information"
}
});
queryObject.query.@bool.should.Add(
new Should() {
match = new() {
level = "error"
}
}
);

Console.WriteLine(JsonConvert.SerializeObject(queryObject));
// Outputs: {"size":1000,"query":{"bool":{"should":[{"match":{"level":"information"}},{"match":{"level":"error"}}],"filter":null,"minimum_should_match":0}}}
}
}

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Match
{
public string level { get; set; }
}

public class Should
{
public Match match { get; set; }
}

public class Timestamp
{
public DateTime gte { get; set; }
public DateTime lt { get; set; }
}

public class Range
{
[JsonProperty("@timestamp")]
public Timestamp Timestamp { get; set; }
}

public class Filter
{
public Range range { get; set; }
}

public class Bool
{
public List<Should> should { get; set; }
public List<Filter> filter { get; set; }
public int minimum_should_match { get; set; }
}

public class Query
{
public Bool @bool { get; set; }
}

public class Root
{
public Root()
{
size = 1000;
query = new();
query.@bool = new();
query.@bool.should = new();
// skipping the rest ...
}

public int size { get; set; }
public Query query { get; set; }
}

https://dotnetfiddle.net/YhFM1I

c# include a variable in a string of data for JSON

If you're trying to make a JSON object. You are better off creating a class that is a blueprint for the JSON object. Then use NewtonSoft to convert to a JSON string.


namespace example
{
public class Ticket
{
public int Id { get; set; }
public string Description { get; set; }
}
class Program
{
static void Main(string[] args)
{
Ticket tic = new Ticket()
{
Id = 123,
Description = "hello motto"
};

Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(tic));
Console.ReadLine();
}
}
}

yields the results

{"Id":123,"Description":"hello motto"}

Also note that you can put classes in classe and it will nest it correctly.

How to "pass" a variable value to a JSON dynamic object?

So i managed to do this by modifying the JSON format, i did it like this

{"People":[
{
"name": "",
"icon": "",
"background": ""
},
{
"name": "",
"icon": "",
"background": ""
},
{
"name": "",
"icon": "",
"background": ""
}]
}

So then I can use Foreach to get to the value

Store Hardcoded JSON string to variable

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"": """"}}";

Passing variables into verbatim string literal for JSON request body

Create an object and use a serializer to construct your Json:

var obj = new
{
Key1 = "value1",
Key2 = "value2"
};

var json = JsonConvert.SerializeObject(obj);


Related Topics



Leave a reply



Submit