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);
}
}
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 an embedded JSON string to a JSON Object in C#
If you know the json response, you can create a model class for it. On VS 2022 you can right click on editor and do paste special Edit --> Paste special --> Paste JSON as Classes
. You should get something like below.
public class Model
{
public object[] paymentId { get; set; }
public object[] paymentRequestId { get; set; }
public object[][][] paymentAmount { get; set; }
public object[] paymentStatus { get; set; }
public object[][][] result { get; set; }
}
After using that Model
class in your code, your code should look like below
using System.Text.Json;
public Model InquiryPaymentAPI(string id)
{
string paymentInfo = PaymentInquiry.IPayment(id);
return JsonSerializer.Deserialize<Model>(paymentInfo);
}
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
Converting a string to JSON in C#
First, create your data model. You can use json2sharp, very helpful tool.
public class Item
{
public int id { get; set; }
public string title { get; set; }
public int position_x { get; set; }
public int position_y { get; set; }
public int position_z { get; set; }
public int rotation_x { get; set; }
public int rotation_y { get; set; }
public int rotation_z { get; set; }
public string created { get; set; }
}
Next use Newtonsoft.Json
and call deserialize method.
var list = JsonConvert.DeserializeObject<List<Item>>(Yourjson);
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);
Cannot convert JSON string to List of object
This is because you need a container class at the top that has this list of orders as a property inside of it:
public class MyData
{
public List<FoodItem> Orders { get; set; }
{
var data = JsonConvert.DeserializeObject<MyData>(strProductsInCart);
var items = data.Orders;
Also, make sure you have public properties that match the name in the JSON. They can be Pascal case, too.
Convert JSON String To C# Object
It looks like you're trying to deserialize to a raw object. You could create a Class that represents the object that you're converting to. This would be most useful in cases where you're dealing with larger objects or JSON Strings.
For instance:
class Test {
String test;
String getTest() { return test; }
void setTest(String test) { this.test = test; }
}
Then your deserialization code would be:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Test routes_list =
(Test)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
More information can be found in this tutorial:
http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx
Related Topics
Generic List of Generic Objects
Passing Parameters to Xslt Stylesheet via .Net
Non-Blocking Read from Standard I/O in C#
Sortable Jqgrid Using Linq to MySQL (Dblinq) and Dynamic Linq - Orderby Doesn't Work
Convert.Toint32() a String with Commas
String Compare C# - Whole Word Match
How to Segment the Elements Iterated Over in a Foreach Loop
Multicast Delegate of Type Func (With Return Value)
No Itemchecked Event in a Checkedlistbox
How to Draw a Rounded Rectangle in C#
How to Upload Files Using Ajax to ASP.NET MVC Controller Action
Nhibernate How to Query Against an Ilist<String> Property
Using String as a Lock to Do Thread Synchronization
Specified Key Is Not a Valid Size for This Algorithm
Caching the Result from a [N Async] Factory Method Iff It Doesn't Throw