How to Turn a C# Object into a Json String in .Net

How do I turn a C# object into a JSON string in .NET?

Please Note

Microsoft recommends that you DO NOT USE JavaScriptSerializer

See the header of the documentation page:

For .NET Framework 4.7.2 and later versions, use the APIs in the System.Text.Json namespace for serialization and deserialization. For earlier versions of .NET Framework, use Newtonsoft.Json.



Original answer:

You could use the JavaScriptSerializer class (add reference to System.Web.Extensions):

using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);

A full example:

using System;
using System.Web.Script.Serialization;

public class MyDate
{
public int year;
public int month;
public int day;
}

public class Lad
{
public string firstName;
public string lastName;
public MyDate dateOfBirth;
}

class Program
{
static void Main()
{
var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = new JavaScriptSerializer().Serialize(obj);
Console.WriteLine(json);
}
}

Converting C# Objects to Json format

You didn't write which version of asp .net core you use.

In version 2.0 Json Newtonsoft library is used to handle json serialization/deserialization.

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
// {
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Sizes": [
// "Small"
// ]
// }

In version 3.0 has been introduced new default library for handling json operations System.Text.Json, but you can change configuration to still use Newtonsoft. Example usage of the System.Text.Json.

string jsonString;
jsonString = JsonSerializer.Serialize(weatherForecast);
// {
// "Date": "2019-08-01T00:00:00-07:00",
// "TemperatureCelsius": 25,
// "Summary": "Hot",
// "DatesAvailable": ["2019-08-01T00:00:00-07:00",
// "2019-08-02T00:00:00-07:00"],
// "TemperatureRanges": {
// "Cold": {
// "High": 20,
// "Low": -10
// },
// "Hot": {
// "High": 60,
// "Low": 20
// }
// },
// "SummaryWords": ["Cool",
// "Windy",
// "Humid"]
// }

Convert object to JSON string in C#

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.

public class ReturnData 
{
public int totalCount { get; set; }
public List<ExceptionReport> reports { get; set; }
}

public class ExceptionReport
{
public int reportId { get; set; }
public string message { get; set; }
}


string json = JsonConvert.SerializeObject(myReturnData);

Convert C# Object to Json Object

To create correct JSON first you need to prepare appropriate model. It can be something like that:

[DataContract]
public class Customer
{
[DataMember(Name = "gors_descr")]
public string ProductDescription { get; set; }

[DataMember(Name = "b_name_first")]
public string Fname { get; set; }

[DataMember(Name = "b_name_last")]
public string Lname { get; set; }
}

To be able to use Data attributes you will need to choose some other JSON serializer. For example DataContractJsonSerializer or Json.NET(I will use it in this example).

Customer customer = new Customer
{
ProductDescription = tbDescription.Text,
Fname = tbFName.Text,
Lname = tbLName.Text
};


string creditApplicationJson = JsonConvert.SerializeObject(
new
{
jsonCreditApplication = customer
});

So jsonCreditApplication variable will be:

{
"jsonCreditApplication": {
"gors_descr": "Appliances",
"b_name_first": "Marisol",
"b_name_last": "Testcase"
}
}

How to convert C# class object to json?

I believe you are new to this and want a working sample to kick off the work.

Here you go.

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

public class Program
{
public static void Main()
{
var o = new UserResponse();
o.Age = "25";
o.Gender = "Male";
o.Message = "Hello";
o.UserInfo = new User();
o.UserInfo.Id = 1;
o.UserInfo.FirstName = "John";
o.UserInfo.LastName = "Doe";
o.UserInfo.Balance = 1000M;
var json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()} );
Console.WriteLine(json);
}
}

public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName{ get; set; }
public decimal Balance { get; set; }
}

public class UserResponse
{
public User UserInfo { get; set; }
public string Age { get; set; }
public string Gender { get; set; }
public string Message { get; set; }
}

Try it out here...

Sample Code

Convert JSON object to Model in .NET

You define AgreementNumber, ClientNumber as strings in your C# code, but this properties is numbers in json, so you have to define it as longs.

And the another point is that you don't need a wrapper around DebtConfirmation class. Deserealize your json into ICollection, IList or just List of DebtConfirmation objects.

I used the quicktype.io for retrieving C# classes from json example you provide. This is very helpful for those who doesn't want to manually generate the models for their JSON strings.

Here is the code sample.

The output is:

789
866
using System.Text.Json;
using System.Text.Json.Serialization;

string json = "[\n {\n \"batchId\": 789,\n \"debtId\": 1841,\n \"dateAdded\": \"2021-07-27T16:01:39.41\",\n \"debtCategoryId\": 2,\n \"agreementNumber\": 78262155,\n \"clientNumber\": 1068055,\n \"clientName\": \"Client Two\"\n },\n {\n \"batchId\": 866,\n \"debtId\": 1918,\n \"dateAdded\": \"2021-08-25T14:47:18.13\",\n \"debtCategoryId\": 2,\n \"agreementNumber\": 1000140792,\n \"clientNumber\": 11213287,\n \"clientName\": \"Client One\"\n }\n]";
var data = JsonSerializer.Deserialize<ICollection<DebtConfirmation>>(json);
foreach (DebtConfirmation current in data)
{
Console.WriteLine(current.BatchId);
}


public partial class DebtConfirmation
{
[JsonPropertyName("batchId")]
public long BatchId { get; set; }

[JsonPropertyName("debtId")]
public long DebtId { get; set; }

[JsonPropertyName("dateAdded")]
public DateTimeOffset DateAdded { get; set; }

[JsonPropertyName("debtCategoryId")]
public long DebtCategoryId { get; set; }

[JsonPropertyName("agreementNumber")]
public long AgreementNumber { get; set; }

[JsonPropertyName("clientNumber")]
public long ClientNumber { get; set; }

[JsonPropertyName("clientName")]
public string ClientName { get; set; }
}

Convert JSON String to JSON Object c#

JObject defines method Parse for this:

JObject json = JObject.Parse(str);

You might want to refer to Json.NET documentation.

How to convert String response (Text) to JSON response in .net core

Please have a read over Format response data in ASP.NET Core Web API. There are multiple possibilities, depending on what your exact requirements are.

The simplest option is to add [Produces] attribute to the controller action, specifying the type that's returned from the aciton:

[Produces("application/json")]
public IActionResult YourAction(int id) { ... }

The above action will return application/json even when the return type of the action is string.


However, it looks like you're returning two values in the string (InterfaceRecordId and ReceiptId). You can use built-in methods (such as Ok(), BadRequest(), Created(), NotFound(), etc) which convert the object to JSON and return a specific status code.

I would recommend returning an object containing both values, and use a convenience return method (Created() or CreatedAtAction()). The following returns an anonymous object and status code 201:

var successResponse = new 
{
InterfaceRecordId = order.WMWDATA.Receipts.Receipt.InterfaceRecordId,
ReceiptId = order.WMWDATA.Receipts.Receipt.ReceiptId
}

return CreatedAtAction(nameof(YourAction), successResponse);

The CreatedAtAction (and Created) convenience methods return a 201 (created) HTTP Code - so the client will be able to infer that from the status code. And since it's returning an object (rather than a string), the return type defaults to application/json, so there's no need for the [Produces] attribute.



Related Topics



Leave a reply



Submit