Convert following class properties into Json format - c#

I need to convert following Employee.cs class in json format,for that i wrote following code
//Employee.cs(In class file)
public class Employee
{
public string Name { get; set; }
public string Job { get; set; }
public string City { get; set; }
}
//In my MyPage.aspx page
Employee oEmployee1 =
new Employee { Name = "Pini", Job = "111", City = "30" };
Employee oEmployee2 =
new Employee { Name = "Yaniv", Job = "Developer", City = "Hyd" };
Employee oEmployee3 =
new Employee { Name = "Yoni", Job = "Developer", City = "Bglre" };
List<Employee> oList = new List<Employee>() { oEmployee1, oEmployee2, oEmployee3 };
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(oList);
Response.Write("<pre>"+sJSON+"</pre>");
I got following output:
[{"Name":"Pini","Job":"111","City":"30"},{"Name":"Yaniv","Job":"Developer","City":"Hyd"},{"Name":"Yoni","Job":"Developer","City":"Bglre"}]
Is it any other way to convert to json format more effectively and i want to beautify json output

I would use JSON.NET Serializer with Formatting.Indented like below
string result= JsonConvert.SerializeObject(obj, Formatting.Indented);
Output
[
{
"Name": "Pini",
"Job": "111",
"City": "30"
},
{
"Name": "Yaniv",
"Job": "Developer",
"City": "Hyd"
},
{
"Name": "Yoni",
"Job": "Developer",
"City": "Bglre"
}
]

list<Employee> oEmployee=
{
new Employee() { Name = "Pini", Job = "111", City = "30" },
new Employee() { Name = "Pini", Job = "111", City = "30" },
new Employee() { Name = "Pini", Job = "111", City = "30" },
};
var oSerializer=new JavaScriptSerializer();
string sJSON = oSerializer.Serialize(oList);
Response.Write("<pre>"+sJSON+"</pre>");
add the System.Web.Script.Serialization reference
add refer this link
http://matijabozicevic.com/blog/csharp-net-development/csharp-serialize-object-to-json-format-using-javascriptserialization

Related

C# Building Json string, but I'm getting the error "Invalid anonymous type member declarator"

I'm trying to create a Json string like this:
{
"StreetLines": [
"101 Test St",
"Ste 100"
],
"City": "Dallas",
"StateOrProvinceCode": "TX",
"PostalCode": "75999",
"CountryCode": "US"
}
This is my code:
var json = new
{
StreetLines = new
{
toAddress1,
toAddress2
},
new
{
City = toCity,
StateOrProvinceCode = toState,
PostalCode = toZip,
CountryCode = toCountry
}
};
I'm getting the error "Invalid anonymous type member declarator" for the lower part. I'm not sure what the issue is, any advice would be appreciated.
First, note that StreetLines is a JSON array, so you should use a C# array or list:
StreetLines = new[] // notice the "[]"
{
toAddress1,
toAddress2
},
In your JSON, the keys City, StateOrProvinceCode and so on are in the same object as StreetLines, so in your C# code you should not create a new anonymous class for them.
If the JSON were like this:
{
"StreetLines": [
"101 Test St",
"Ste 100"
],
"OtherPartsOfTheAddress": {
"City": "Dallas",
"StateOrProvinceCode": "TX",
"PostalCode": "75999",
"CountryCode": "US"
}
}
Then you can write
var json = new
{
StreetLines = new[]
{
toAddress1,
toAddress2
},
OtherPartsOfTheAddress = new // notice the key name
{
City = toCity,
StateOrProvinceCode = toState,
PostalCode = toZip,
CountryCode = toCountry
}
};
But since there is no OtherPartsOfTheAddress, you just need to do:
var json = new
{
StreetLines = new[]
{
toAddress1,
toAddress2
},
City = toCity,
StateOrProvinceCode = toState,
PostalCode = toZip,
CountryCode = toCountry
};
Your code should look like this,
var json = new
{
StreetLines = new List<string>
{
toAddress1,
toAddress2
},
City = toCity,
StateOrProvinceCode = toState,
PostalCode = toZip,
CountryCode = toCountry
}
StreetLines is a collection of strings and City, Sate, postal etc are part of the main json.

How to Create a new Json using array c#

I need to create the following JSON:
[
{
"Name": [
{
"First Name": "Adam"
},
{
"Last Name": "Smith"
}
]
}
]
Please help as I have tried everything on here and on json.net
Thank you in advance.
Well... it is funny how things work once you know how its done :) and here for those who may have the same problem, this is the way to do it :
JObject myObject =
new JObject(
new JProperty("Name",
new JArray(
new JObject(
new JProperty("First Name", "Adam")),
new JObject(
new JProperty("Last Name", "Smith")))));
JArray myArray = new JArray
myArray.Add(myObject);
EDITED ANSWER: Removed old answer explaining what I thought the issue was with the JSON in the question. Changed to build C# objects that could create the JSON string above, haven't tried this but I think it should work:
Here are the C# classes:
public class Name
{
[JsonProperty(PropertyName = "First Name")]
public string FirstName { get; set; }
[JsonProperty(PropertyName = "Last Name")]
public string LastName { get; set; }
}
public class RootObject
{
[JsonProperty(PropertyName = "Name")]
public List<Name> Name { get; set; }
}
Create the name objects in the RootObject:
var myRootObj = new RootObject();
myRootObj.Name = new List<Name>();
var firstNameObj = new Name() { FirstName = "Adam" };
var secondNameObj = new Name() { LastName = "Smith" };
myRootObj.Name.Add(firstNameObject);
myRootObj.Name.Add(secondNameObject);
Now lets convert this object to JSON:
var json = JsonConvert.SerializeObject(myRootObj, Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
}););
I haven't tried this but I think it should create your JSON string, such as below:
{
"Name": [
{
"First Name": "Adam"
},
{
"Last Name": "Smith"
}
]
}

json.net list serialization to JSON Array

I'm using json.net to serialize an object to a json string. Now I have a list of Objects which I like to serialize into a Json array. However, I'm unable to do that with json.net and hope someone can point out my mistake.
I have the following classes:
class PeopleList {
public Person inputs { get; set; }
}
class Person {
public String name { get; set; }
public int age { get; set; }
}
I'm using the following code to serialize the objects:
var json = new List<PeopleList>();
Person p1 = new Person { name = "Name 1", age = 20 };
json.Add(new PeopleList { inputs = p1 });
Person p2 = new Person { name = "Name 2", age = 30 };
json.Add(new PeopleList { inputs = p2 });
string jsonString = JsonConvert.SerializeObject(json, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented });
This gives me the following output:
[
{
"inputs": {
"name": "Name 1",
"age": 20
}
},
{
"inputs": {
"name": "Name 2",
"age": 30
}
}
]
Here is what I actually want:
[
{
"inputs": [
{
"name": "Name 1",
"age": 20
}
]
},
{
"inputs": [
{
"name": "Name 2",
"age": 30
}
]
}
]
As you see I need every object in my list encapsulated with []. How can I achieve that with Json.net? Thanks!
If you want your inputs to be an array, you need to declare it as an array in your object :
class PeopleList {
public List<Person> inputs { get; set; }
}
Then you can use it :
var json = new List<PeopleList>();
List<Person> p1 = new List<Person> { new Person { name = "Name 1", age = 20 } };
json.Add(new PeopleList { inputs = p1 });
List<Person> p2 = new List<Person> { new Person { name = "Name 2", age = 30 } };
json.Add(new PeopleList { inputs = p2 });
string jsonString = JsonConvert.SerializeObject(json, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented });
based on your output and what you want you probably want to do something like this
Json2CSharpClass Converter
public class Person
{
public string name { get; set; }
public int age { get; set; }
}
public class PeopleList
{
public List<Person> inputs { get; set; }
}

Dataset to JSON using C#/VB.Net

I have a dataset with the following data:
I want to convert this data into JSON in the following format:
{
"Resource": [
{
"resourceID": "1",
"resourceName": "Jonathan",
"Customer": [
{
"customerID": "1",
"firstName": "Alec",
"lastName": "Stewart",
"Appointments": [
{
"appointmentID": "1",
"startDate": "01-01-2015",
"endDate": "01-01-2015"
},
{
"appointmentID": "2",
"startDate": "01-01-2015",
"endDate":"01-01-2015",
}
]
},
{
"customerID": "2",
"firstName": "Chris",
"lastName": "Douglas",
"Appointments": [
{
"appointmentID": "3",
"startDate": "01-01-2015",
"endDate": "01-01-2015",
}
]
}
]
},
{
"resourceID": "2",
"resourceName": "Matthew",
"Customer": [
{
"customerID": "3",
"firstName": "Shirley",
"lastName": "Graham",
"Appointments": [
{
"appointmentID": "4",
"startDate": "01-01-2015",
"endDate": "01-01-2015",
},
{
"appointmentID": "5",
"startDate": "01-01-2015",
"endDate": "01-01-2015"
}
]
},
{
"customerID": "4",
"firstName": "Ricardo",
"lastName": "Powell",
"Appointments": [
{
"appointmentID": "6",
"startDate": "01-01-2015",
"endDate": "01-01-2015"
}
]
}
]
}
]
}
Is there any faster way that I can use in VB.Net to convert it directly to JSON? Should I go with creating classes and list and iterate the dataset to create object of nested classes and then serialize it or it can be achieved in a different way? Can someone tell me about the way to serialize the dataset to JSON? I am okay with C# as well.
As already mentioned, newtonsoft is a real beauty. You could do this:
string json = JsonConvert.SerializeObject(yourdataset, Formatting.Indented);
You need to have nested class like below:
[Serializable]
public class Resource
{
public string resourceID { get; set; }
public string resourceName { get; set; }
public List<Customer> Customers { get; set; }
}
public class Customer
{
public string customerID { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public List<Appointment> Appointments { get; set; }
}
public class Appointment
{
public string appointmentID { get; set; }
public string startDate { get; set; }
public string endDate { get; set; }
}
After you populate the data in your class, you can use JavaScriptSerializer class which is already part of System.Web.Script.Serialization like below:
var resources = new List<Resource>();
//populate resources data here
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
var resourceJSON = serializer.Serialize(resources); //result
//You can populate resources class using code below:
// Fill the DataSet
DataSet dataSet = new DataSet("tblResources");
adapter.Fill(dataSet);
//Populate nested class base on DataSet
var resources = new List<Resource>();
string currentResourceID = string.Empty;
string currentCustomerID = string.Empty;
int totalRows = dataSet.Tables[0].Rows.Count;
var resource = new Resource();
var customer = new Customer();
var customers = new List<Customer>();
var appointments = new List<Appointment>();
bool newResource = false;
bool newCustomer = false;
for (int i = 0; i < totalRows; i++)
{
var resourceID = dataSet.Tables[0].Rows[i]["resourceID"].ToString();
var resourceName = dataSet.Tables[0].Rows[i]["resourceName"].ToString();
var customerID = dataSet.Tables[0].Rows[i]["customerID"].ToString();
var firstName = dataSet.Tables[0].Rows[i]["firstName"].ToString();
var lastName = dataSet.Tables[0].Rows[i]["lastName"].ToString();
var appointmentID = dataSet.Tables[0].Rows[i]["appointmentID"].ToString();
var startDate = dataSet.Tables[0].Rows[i]["startDate"].ToString();
var endDate = dataSet.Tables[0].Rows[i]["endDate"].ToString();
if (!currentResourceID.Equals(resourceID))
{
currentResourceID = resourceID;
resource = new Resource()
{
resourceID = resourceID,
resourceName = resourceName
};
resources.Add(resource);
newResource = true;
}
else
{
newResource = false;
}
if (newResource)
{
customers = new List<Customer>();
resource.Customers = customers;
currentCustomerID = string.Empty;
}
if (!currentCustomerID.Equals(customerID))
{
currentCustomerID = customerID;
customer = new Customer()
{
customerID = customerID,
firstName = firstName,
lastName = lastName
};
customers.Add(customer);
newCustomer = true;
}
else
{
newCustomer = false;
}
if (newCustomer)
{
appointments = new List<Appointment>();
customer.Appointments = appointments;
}
var appointment = new Appointment()
{
appointmentID = appointmentID,
startDate = startDate,
endDate = endDate
};
appointments.Add(appointment);
}
//Convert nested class to json
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
var resourceJSON = serializer.Serialize(resources);
Use for .NET <> JSON Newtonsofts JSON at http://www.newtonsoft.com/json. It does everything and more what you need!
As mentioned u can use NewtonSoft for this. But there is no default behavior for this. To create a more generic solution u can write a Custom JsonConverter for the Newtonsoft. And implement a clean way for your project to serialize or deserialize.
See a example at: http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization/ or http://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm.

Adding data to ObservableCollection in WPF

I have some problem here. Here it is:
I have this class
public class NewsFeedResources
{
public string Name { get; set; }
public string Id { get; set; }
public string Message { get; set; }
public static ObservableCollection<NewsFeedResources> _newsfeed = new ObservableCollection<NewsFeedResources>
{
new NewsFeedResources { Name = "Joe", Id = "1", Message="Foo" },
new NewsFeedResources { Name = "Wandy", Id = "2", Message="Bar" },
new NewsFeedResources { Name = "Yuliana", Id = "3", Message="Baz" },
new NewsFeedResources { Name = "Hardi", Id = "4", Message="Baz" },
};
public static ObservableCollection<NewsFeedResources> newsFeedResources
{ get { return _newsfeed; }
}
}
If I have another data such as
Name=John, Id=5, Message="Stack overflow"
Name=Jane, Id=6, Message="Hello world"
How can I add the data into the class, but not from the constructor? Thanks for the help
ObservableCollection exposes the Collection<T>.Add Method:
Adds an object to the end of the Collection.
So you'd have:
_newsfeed.Add(new NewsFeedResources {Name = "John",
Id = 5,
Message = "Stack overflow"});
_newsfeed.Add(new NewsFeedResources {Name = "Jane",
Id = 6,
Message = "Hello world"});
(typed from memory)
call a function from constructor or anywhere as u like and add items like below
NewsFeedResources NFR=new NewsFeedResources(){Name=John, Id=5, Message="Stack overflow"};
_newsfeed.add(NFR);
NewsFeedResources NFR1 =new NewsFeedResources(){Name=Jane, Id=6, Message="Hello world"};
_newsfeed.add(NFR);

Categories