Converting Json to .NET Object collection - json

As part of my WCF service, i convert my DataTable into a JSON. On client side, I want to able to convert this JSON response into a .NET collection. I want to be able to keep it dynmaic, and bind it to a data grid. I am trying figure out the best way to do this. Thanks jay

Define a collection and a class whose properties match the JSON data - then use the JavaScriptSerializer class. Then just bind your grid to the collection:
class ACollection
{
public IEnumerable<SomeClass> SomeClassList { get; set; }
}
class SomeClass
{
public string Field { get; set; }
}
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
ACollection list = jsSerializer.Deserialize<ACollection>(jsonString);

Related

Is there a setting to keep empty lists during JSON serialization in ServiceStack?

As the title says, is there a way to keep empty lists during JSON serialization in ServiceStack?
ServiceStack.Text JSON Serializer, already serializes empty lists by default:
using ServiceStack;
using ServiceStack.Text;
Console.WriteLine(new Test().ToJson());
public class Test
{
public List<string> List { get; set; } = new();
}
Output:
{"List":[]}

JSON string to actual JSON

Using .Net core 2.2, I am building an API that returns JSON data from my stored procedure (using FOR JSON PATH), I return a value that looks like:
[{"ID":213,"SizeCode":"Small"},{"ID":257,"SizeCode":"S/M"},{"ID":214,"SizeCode":"Medium",},{"ID":215,"SizeCode":"Large"}]
So when I map it to my object to return from the API
public class Details
{
public string SizeChart { get; set; }
}
,it returns this:
"[{'ID':213,'SizeCode':'Small'},{'ID':257,'SizeCode':'S/M'},{'ID':214,'SizeCode':'Medium',},{'ID':215,'SizeCode':'Large'}]"
I don't want the double quotes around it, so I figure the actual property shouldn't be a string. Is there a better data type to use or a way to return without the double quotes?
You need to parse string into JSON object (actually in your case - JArray as it is an array) and return it from your API:
JArray a = JArray.Parse(jsonString);
So it might look like
public class Details
{
public string SizeChart { get; set; }
public JArray SizeChartJArray {
get {
return JObject.Parse(SizeChart);
}
}
}

How to enumerate json string in MVC Razor foreach loop?

I'm using SQL Server 2016 to return json data in a string field in my data set. I passed the json string to the model without any conversions. I want to enumerate my json string field in MVC razor like:
#foreach (var notification in Model.AccountSettings.EmailNotifications)
{
EmailNotifications is a json array of objects.
EmailNotifications = [{"EmailNotificationID":8,"EmailNotificationName":"Any new KLAS report is published.","IsSet":false},{"EmailNotificationID":9,"EmailNotificationName":"KLAS publishes a report in one of my areas of interest.","IsSet":false}]
What the best way to do this?
The clean solution is to create a class to represent each item in your JSON array, convert your string to a list of this class and enumerate that.
public class NotificationItem
{
public int EmailNotificationID { get; set; }
public string EmailNotificationName { get; set; }
public bool IsSet { get; set; }
}
And you may use Newtonsoft.Json.JsonConvert.DeserializeObject method to convert the json string to list of NotificationItem objects.
#{
var items = Newtonsoft.Json.JsonConvert
.DeserializeObject<List<NotificationItem>>("yourJsonStringHere");
}
#foreach (var item in items)
{
<p>#item.EmailNotificationID</p>
<p>#item.EmailNotificationName </p>
}

Entity framework serialize POCO to JSON

I'm using Ef 4.1 and I've got a POCO object I'd like to serialize to JSON, I've read there is a problem to do so when using lazy loading but I'm not sure I can because a Message can have a collection of Message.
Is there any way to do this? sirialize this kind of object into JSON?
My Message object looks like:
public class Message
{
[Key]
public int Id { get; set; }
public int? ParentId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? LastModified { get; set; }
public virtual User User { get; set; }
public virtual Message Parent { get; set; }
public virtual ICollection<Message> Children { get; set; }
}
The problem is circular references. An easy way to avoid this is to use Json.Net http://james.newtonking.com/projects/json-net.aspx instead of the default MVC json serializer. The latest version of Json.Net will serialize objects with circular references out of the box. http://james.newtonking.com/projects/json/help/PreserveObjectReferences.html for more info on the problem
Eager load it using Include(). Sample linq:
var serializeMe = (from m in MyContext.Message.Include("User") where m.Id == someValue select m).ToList();
That will tell EF to load the User navigation property right away instead of lazy loading it, and the serializer should have no problem with it then.
How about this:
Mark your class as [Serializable]
Use the JsonSerializer to serialize your object to JSON.
Perhaps use eager loading on the properties in your EF query?
Message msg = new Message();
var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(msg.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, msg);
string json = Encoding.Default.GetString(ms.ToArray());
[Serializable]
public class Message
{
}
Well, lets go by parts.
¿Why is happening this?
Because you have virtual properties. If you are using EF you actually need them if you are using Lazy loading. You can configurate your EF to not do this by this example:
context.Configuration.ProxyCreationEnabled = false;
where context is your ObjectContext or DbContext... this assuming you are using EF. But for most scenarios this is not a good aproach.
Possible Solution
As I always say: "there are not good or bad solutions, just different ways and it depends on the context", saying that, you can create dynamic objects.
In case you only have to serialize a unique object, you can do something like this
Json(new {#property1=yourObject.property1, #property2=yourObject.property2})
In case you have a list, well, you can do this:
var list = new List<dynamic>();
foreach(var item in myRepository.GetAll())
{
list.Add(new
{
#property1= item.property1,
#property2= item.property2,
#property3= item.property3
});
}
return Json(list, JsonRequestBehavior.DenyGet);
I tried to make this as generic as I can. I hope this can help somebody!!
Best regards and have a very nice day! :)

use of the DataContractJsonSerializer to convert datatable to json

I want to use .Net Framework built-in library to convert my DataTable / DataSet to JSON. How is this possible.
DataTable and DataSet objects cannot be JSON serialized directly. You'll need to convert them first to something like
IDictionary<string, IEnumerable<IDictionary<string, object>>>
Once you do that, you can use JavaScriptSerializer to do the actual conversion to JSON.
Update based on your comment:
If you are trying to convert the data obtained from a SQL query into JSON, represent the data in a simple class first:
public class Employee
{
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Read the results into:
List<Employee>
Now, convert the list to JSON using JavaScriptSerializer.