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"
}
}
Another way.
using System;
using Newtonsoft.Json;
namespace MyNamepace
{
public class MyCustomObject
{
public MyCustomObject()
{
}
[JsonProperty(PropertyName = "my_int_one")]
public int MyIntOne { get; set; }
[JsonProperty(PropertyName = "my_bool_one")]
public bool MyBoolOne { get; set; }
}
}
and
/* using Newtonsoft.Json; */
MyCustomObject myobj = MyCustomObject();
myobj.MyIntOne = 123;
myobj.MyBoolOne = false;
string jsonString = JsonConvert.SerializeObject(
myobj,
Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});
see
http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonSerializerSettings.htm
My packages.config at the time of writing...though I'm sure future/latest versions will still support it:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
</packages>