How to Create Json String in C#

How to create JSON string in C#

You could use the JavaScriptSerializer class, check this article to build an useful extension method.

Code from article:

namespace ExtensionMethods
{
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}

public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
}

Usage:

using ExtensionMethods;

...

List<Person> people = new List<Person>{
new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}
};


string jsonString = people.ToJSON();

How to create JSON object in C#

Try That:

using System.Text.Json;

var obj = new
{
files = new[]
{
new
{
file_path = "example.txt",
content ="source code \n with multiple lines\n"
}
}
};
var json = JsonSerializer.Serialize(obj);
Console.WriteLine(json);

Result:

Sample Image

Create JSON string in c#


var obj = new {tafsir = new Dictionary<string, object>{
{"1_1", new{text="Some text here"}},
{"1_2", new{text="Some text here2"}}
}
};

var json = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);

Create JSON object from string in C#

In the most recent version of .NET we have the System.Text.Json namespace, making third party libraries unecessary to deal with json.

using System.Text.Json;

And use the JsonSerializer class to serialize:

var data = GetData();
var json = JsonSerializer.Serialize(data);

and deserialize:

public class Person
{
public string Name { get; set; }
}

...
var person = JsonSerializer.Deserialize<Person>("{\"Name\": \"John\"}");

Other versions of .NET platform there are different ways like the JavaScriptSerializer where the simplest way to do this is using anonymous types, for sample:

string json = new JavaScriptSerializer().Serialize(new
{
message = new { text = "test sms" },
endpoints = new [] {"dsdsd", "abc", "123"}
});

Alternatively, you can define a class to hold these values and serialize an object of this class into a json string. For sample, define the classes:

public class SmsDto
{
public MessageDto message { get; set; }

public List<string> endpoints { get; set; }
}

public class MessageDto
{
public string text { get; set; }
}

And use it:

var sms = new SmsDto()
{
message = new MessageDto() { text = "test sms" } ,
endpoints = new List<string>() { "dsdsd", "abc", "123" }
}

string json = new JavaScriptSerializer().Serialize(sms);

Create Json string using JsonObject in C#

I found the answer almost immediately after posting this.

I found the JsonValue.CreateStringValue method

 var jsonValue = JsonValue.CreateStringValue(record.Value);

I could then pass this into the Add method on the JsonObject.

How to write JSON string value in code?

You have to do this

String str="{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";


Please see this for reference
Also from msdn :)

Short Notation  UTF-16 character    Description
\' \u0027 allow to enter a ' in a character literal, e.g. '\''
\" \u0022 allow to enter a " in a string literal, e.g. "this is the double quote (\") character"
\\ \u005c allow to enter a \ character in a character or string literal, e.g. '\\' or "this is the backslash (\\) character"
\0 \u0000 allow to enter the character with code 0
\a \u0007 alarm (usually the HW beep)
\b \u0008 back-space
\f \u000c form-feed (next page)
\n \u000a line-feed (next line)
\r \u000d carriage-return (move to the beginning of the line)
\t \u0009 (horizontal-) tab
\v \u000b vertical-tab

How to create my json string by using C#?

The json is kind of odd, it's like the students are properties of the "GetQuestion" object, it should be easy to be a List.....

About the libraries you could use are.

  • JavaScriptSerializer
  • NewtonSoft.Json
  • SimpleJson
    ...

And there could be many more, but that are what I've used

About the json I don't now maybe something like this

public class GetQuestions
{
public List<Student> Questions { get; set; }
}

public class Student
{
public string Code { get; set; }
public string Questions { get; set; }
}

void Main()
{
var gq = new GetQuestions
{
Questions = new List<Student>
{
new Student {Code = "s1", Questions = "Q1,Q2"},
new Student {Code = "s2", Questions = "Q1,Q2,Q3"},
new Student {Code = "s3", Questions = "Q1,Q2,Q4"},
new Student {Code = "s4", Questions = "Q1,Q2,Q5"},
}
};

//Using Newtonsoft.json. Dump is an extension method of [Linqpad][4]
JsonConvert.SerializeObject(gq).Dump();
}

Linqpad

and the result is this

{
"Questions":[
{"Code":"s1","Questions":"Q1,Q2"},
{"Code":"s2","Questions":"Q1,Q2,Q3"},
{"Code":"s3","Questions":"Q1,Q2,Q4"},
{"Code":"s4","Questions":"Q1,Q2,Q5"}
]
}

Yes I know the json is different, but the json that you want with dictionary.

void Main()
{
var f = new Foo
{
GetQuestions = new Dictionary<string, string>
{
{"s1", "Q1,Q2"},
{"s2", "Q1,Q2,Q3"},
{"s3", "Q1,Q2,Q4"},
{"s4", "Q1,Q2,Q4,Q6"},
}
};

JsonConvert.SerializeObject(f).Dump();
}

class Foo
{
public Dictionary<string, string> GetQuestions { get; set; }
}

And with Dictionary is as you want it.....

{
"GetQuestions":
{
"s1":"Q1,Q2",
"s2":"Q1,Q2,Q3",
"s3":"Q1,Q2,Q4",
"s4":"Q1,Q2,Q4,Q6"
}
}

How to create JSON from strings without creating a custom class using JSON.Net library

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

Create JSON object using System.Text.Json

In .NET 5 you can use a combination of dictionaries and anonymous types to construct free-form JSON on the fly. For instance, your sample code can be rewritten for System.Text.Json as follows:

var json = new Dictionary<string, object>
{
["Status"] = result.Status.ToString(),
["Duration"] = result.TotalDuration.TotalSeconds.ToString(NumberFormatInfo.InvariantInfo),
};

var entries = result.Entries.ToDictionary(
d => d.Key,
d => new { Status = d.Value.Status.ToString(), Duration = d.Value.Duration.TotalSeconds.ToString(NumberFormatInfo.InvariantInfo), Description = d.Value.Description } );
if (entries.Count > 0)
json.Add("result", entries);

var newJson = JsonSerializer.Serialize(json, new JsonSerializerOptions { WriteIndented = true });

Notes:

  • When constructing a JSON object with properties whose values have mixed types (like the root json object in your example) use Dictionary<string, object> (or ExpandoObject, which implements Dictionary<string, object>).

    You must use object for the value type because System.Text.Json does not support polymorphism by default unless the declared type of the polymorphic value is object. For confirmation, see How to serialize properties of derived classes with System.Text.Json:

    You can get polymorphic serialization for lower-level objects if you define them as type object.


  • When constructing a JSON object with a fixed, known set of properties, use an anonymous type object.

  • When constructing a JSON object with runtime property names but fixed value types, use a typed dictionary. Oftentimes LINQ's ToDictionary() method will fit perfectly, as is shown above.

  • Similarly, when constructing a JSON array with values that have mixed types, use List<object> or object []. A typed List<T> or T [] may be used when all values have the same type.

  • When manually formatting numbers or dates as strings, be sure to do so in the invariant locale to prevent locale-specific differences in your JSON.

Demo fiddle here.

Create JSON manually

You need to add JObject into the array like so. I imagine you you will have to add whatever condition properties (or other nested objects) you want

var jArray = new JArray();
var nik = new JObject();
nik["Name"] = "nik";
nik["Age"] = "17";
nik["Country"] ="Germany";

jArray.Add(nik);
JObject o = new JObject();
o["Value"] = jArray;

string json = o.ToString();

depending on the exact nature of your dynamic content, you can use intializer code like

    var jArray = new JArray
{
new JObject {["Name"] = "nik", ["Age"] = "17", ["Country"] = "Germany"},
new JObject {["Name"] = "bob", ["Age"] = "32", ["Country"] = "New Zealand"}
};
var o = new JObject {["Value"] = jArray};


Related Topics



Leave a reply



Submit